🔍 Difference between Arrays.asList() and List.of() in Java Let’s understand this with a simple example 👇 List<Integer> ls = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> lst = List.of(1, 2, 3, 4, 5, 6); ✅ Case 1: Arrays.asList() 1️⃣ Change value using index ls.set(0, 100); Output [100, 2, 3, 4, 5, 6] 2️⃣ Try to add a new element ls.add(7); ❌ UnsupportedOperationException 3️⃣ Try to remove an element ls.remove(2); ❌ UnsupportedOperationException 🔎 Analysis Arrays.asList() returns a fixed-size list It is backed by an array ✅ You can modify elements using set() ❌ You cannot add or remove elements ✅ null values are allowed 📌 Introduced in Java 1.2 ✅ Case 2: List.of() 1️⃣ Try to change value lst.set(0, 100); ❌ UnsupportedOperationException 2️⃣ Try to add a new element lst.add(7); ❌ UnsupportedOperationException 3️⃣ Try to remove an element lst.remove(1); ❌ UnsupportedOperationException 🔎 Analysis List.of() creates a fully immutable list ❌ You cannot add, remove, or modify ❌ null values are not allowed 📌 Introduced in Java 9 ❓ Main Question: When to use which? ✅ Use List.of() When you need a read-only / immutable list, such as: List<String> roles = List.of("ADMIN", "USER", "MANAGER"); ✔ Best for constants ✔ Prevents accidental modification ✔ Cleaner & safer code Arrays.asList() allows value modification but not size change, whereas List.of() creates a completely immutable list. #Java #JavaInterview #Collections #BackendDevelopment #SpringBoot #HappyLearning #JavaLearner #JVM
Arrays.asList() vs List.of() in Java: Immutable vs Modifiable Lists
More Relevant Posts
-
📘 Core Java – Day 5 Topic: Loops (for loop & simple pattern) Today, I learned about the concept of Loops in Core Java. Loops are used to execute a block of code repeatedly, which helps in reducing code redundancy and improving efficiency. In Java, the main types of loops are: 1. for loop 2. while loop 3. do-while loop 4. for-each loop 👉 I started by learning the for loop. 🔹 Syntax of for loop: for(initialization; condition; increment/decrement) { // statements } 🔹 Working of for loop: Initialization – initializes the loop variable (executed only once) Condition – checked before every iteration Execution – loop body runs if the condition is true Increment/Decrement – updates the loop variable Loop continues until the condition becomes false ⭐ Example: Simple Star Pattern using for loop for(int i = 1; i <= 5; i++) { for(int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); } Output: * * * * * * * * * * * * * * * 🔹 Key Points: ✔ for loop is used when the number of iterations is known ✔ It keeps code structured and readable ✔ Nested for loops are commonly used in pattern programs 🚀 Building strong fundamentals in Core Java, one concept at a time. #CoreJava #JavaLoops #ForLoop #JavaProgramming #LearningJourney #Day5
To view or add a comment, sign in
-
Hi everyone 👋 Continuing the weekend Java Keyword Series with another important keyword 👇 📌 Java Keyword Series – Part 2 ✅ super keyword in Java The super keyword is used to refer to the immediate parent class object 👇 🔹 Why do we use super? To access parent class variables To call parent class methods To call the parent class constructor 🔹 Where can we use super? 1️⃣ Access parent class variable class Parent { int x = 10; } class Child extends Parent { int x = 20; void show() { System.out.println(super.x); // prints 10 } } 2️⃣ Call parent class method class Parent { void display() { System.out.println("Parent method"); } } class Child extends Parent { void display() { super.display(); // calls parent method System.out.println("Child method"); } } 3️⃣ Call parent class constructor class Parent { Parent() { System.out.println("Parent constructor"); } } class Child extends Parent { Child() { super(); // calls parent constructor } } 🔹 In simple words super is used to access or call members of the parent class. 👉 🧠 Quick Understanding super.variable → parent variable super.method() → parent method super() → parent constructor #Java #CoreJava #JavaKeywords #LearningInPublic #BackendDevelopment
To view or add a comment, sign in
-
Day 11 - What I Learned In a Day(JAVA) Today I learned that Java variables are classified into two areas and understood their scope. 1️⃣ Global Area (Instance Variable) Declared inside the class but outside methods. Accessible by all methods inside the class. Scope: Entire class. Memory is created when the object is created. 2️⃣ Local Area (Local Variable) Declared inside a method, constructor, or block. Accessible only inside that method or block. Scope: Limited to that block only. Memory is created when the method runs. Types of Variables in Java (Based on Scope): 1️⃣ Local Variable Declared inside a method. Used only inside that method. Cannot be used outside the method. 2️⃣ Non-Static Variable (Instance Variable) Declared inside the class but outside methods. Belongs to the object. Each object has its own copy. 3️⃣Static Variable Declared using static keyword. Belongs to the class. One copy is shared by all objects. Three Important Statements in Java (Variables): 1️⃣ Declaration Creating a variable. You are telling Java the type and name of the variable. No value is given. Example: int a; 2️⃣ Initialization Giving a value to a variable. The variable must already be declared. Example: a = 10; 3️⃣ Declaration + Initialization Creating the variable and giving value at the same time. Example: int a = 10; Practiced 👇 #Java #Variables #Programming #CodingJourney
To view or add a comment, sign in
-
🕵️♂️☕ GUESS THE JAVA VERSION: CAN YOU SPOT IT? 🔸 TLDR ▪️ If you see var in Java local variables → think Java 10+ ☕🧠 🔸 THE QUIZ (GUESS BEFORE READING THE ANSWER) import java.util.*; class Example { void test() { var x = 10; var s = "hello"; var list = new ArrayList<String>(); for (var item : list) {} for (var i = 0; i < 10; i++) {} try (var r = new java.io.StringReader("")) {} } } 🔸 OPTIONS ▪️ Java 1 ▪️ Java 2 ▪️ Java 10 ▪️ Java 13 ▪️ Java 16 🔸 ANSWER ✅ Java 10 🔸 WHY? (VERY SHORT) ▪️ The giveaway is var: local-variable type inference was introduced in Java 10 (JEP 286). ▪️ You can use var for local variables, for-loop indexes, enhanced for, and try-with-resources variables (as shown here). 🔸 TAKEAWAYS ▪️ var reduces boilerplate while keeping Java statically typed ✅ ▪️ Works only for local variables (not fields / params) ▪️ Requires an initializer (no initializer = nothing to infer) ▪️ The inferred type is a real compile-time type, not “dynamic typing” #Java #Java10 #JVM #CleanCode #SoftwareEngineering #Programming #JavaDevelopers #Backend #DevTips #CodeQuality #Learning Go further with Java certification: Java👇 https://lnkd.in/eZKYX5hP Spring👇 https://lnkd.in/eADWYpfx SpringBook👇 https://lnkd.in/en7CvPmi
To view or add a comment, sign in
-
-
Core Java Deep-Dive — Part 2: Object-Oriented Foundations and Practical Examples Continuing from Part 1: urn:li:share:7426958247334551553 Hook Ready to move from basics to mastery? In Part 2 we'll focus on the object-oriented foundations every Java developer must master: classes and objects, inheritance, polymorphism, abstraction, encapsulation, interfaces, exception handling, and a practical introduction to collections and generics. Body Classes and Objects — How to model real-world entities, constructors, lifecycle, and best practices for immutability and DTOs. Inheritance & Interfaces — When to use inheritance vs composition, interface-based design, default methods, and practical examples. Polymorphism — Method overriding, dynamic dispatch, and designing for extensibility. Abstraction & Encapsulation — Hiding implementation details, access modifiers, and API boundaries. Exception Handling — Checked vs unchecked exceptions, creating custom exceptions, and robust error handling patterns. Collections & Generics — Choosing the right collection, performance considerations, and type-safe APIs with generics. Each topic will include concise Java code examples, small practice problems to try locally, and pointers for where to find runnable samples and exercises in the next threaded posts. Call to Action What Java OOP topic do you want a runnable example for next? Tell me below and I’ll include code and practice problems in the following thread. 👇 #Java #CoreJava #FullStack #Programming #JavaDeveloper
To view or add a comment, sign in
-
🔹 Today I learned about Strings in Java • A String is a sequence of characters enclosed in double quotes. • In Java, Strings are objects used to store and manipulate text. 🔹 Types of Strings • Immutable Strings – Once created, their value cannot be changed Examples: name, date of birth, gender • Mutable Strings – Their value can be changed Examples: password, email, months of the year 🔹 Ways to Create Strings • Using new keyword → String s1 = new String("java"); • Without new keyword → String s2 = "java"; 🔹 Memory Allocation (Heap Segment) • String Constant Pool (SCP) – Does not allow duplicate values – Strings created without new are stored here • Heap Area – Allows duplicate objects – Strings created with new are stored in the heap 🔹 Ways to Compare Strings • == → Compares references (memory locations) • equals() → Compares values • compareTo() → Compares strings character by character • equalsIgnoreCase() → Compares values ignoring case differences #TapAcademy #Java #JavaProgramming #LearningJava #StringConcept #ProgrammingBasics #CodingJourney #TechLearning
To view or add a comment, sign in
-
-
🚀 Core Java Insight: Variables & Memory (Beyond Just Syntax) Today’s Core Java session completely changed how I look at variables in Java — not as simple placeholders, but as memory-managed entities controlled by the JVM. 🔍 Key Learnings: ✅ Variables in Java Variables are containers for data Every variable has a clear memory location and lifecycle 🔹 Instance Variables Declared inside a class Memory allocated in the Heap (inside objects) Automatically initialized by Java with default values Examples of default values: int → 0 float → 0.0 boolean → false char → empty character 🔹 Local Variables Declared inside methods Memory allocated in the Stack No default values Must be explicitly initialized — otherwise results in a compile-time error 🧠 How Java Executes in Memory When a Java program runs: Code is loaded into RAM JVM creates a Java Runtime Environment (JRE) JRE is divided into: Code Segment Heap Stack Static Segment Each segment plays a crucial role in how Java programs execute efficiently. 🎯 Why This Matters Understanding Java from a memory perspective helps in: Writing cleaner, safer code Debugging issues confidently Answering interview questions with depth Becoming a developer who understands code — not just runs it 💡 Great developers don’t just write code. They understand what happens inside the system. 📌 Continuously learning Core Java with a focus on fundamentals + real execution behavior. hashtag #Java #CoreJava #JVM #JavaMemory #ProgrammingConcepts #SoftwareEngineering #InterviewPrep #DeveloperJourney #LearningEveryDay
To view or add a comment, sign in
-
-
🚀 Java 8 Streams – A Small Problem That Tests Big Concepts Today I revisited a classic interview question that seems simple but hides some heavy duty concepts: 👉 Find the last repeating character in a string using Java 8 Streams. Example: Input: "programming" Output: g (The repeated chars are 'r', 'g', 'm'. 'g' is the last one to appear in the original sequence.) Here is an elegant way to solve it: Java String input = "programming"; Optional<Character> result = input.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, // Key: Maintains insertion order Collectors.counting() // Value: Frequency count )) .entrySet() .stream() .filter(e -> e.getValue() > 1) .reduce((first, second) -> second) // The "Last" logic .map(Map.Entry::getKey); result.ifPresent(System.out::println); ✨ Why this is a great test of fundamentals: It’s not just about the syntax it’s about what’s happening under the hood: It’s easy to write code that works it’s harder to write code that is both expressive and efficient. I’m curious how would you tackle this 😄? 1️⃣ Stick to the modern Streams approach? 2️⃣ Go back to a traditional for loop for potential performance gains? 3️⃣ Use a different collection entirely? #Java #Java8 #Streams #BackendDevelopment #CodingInterview #SoftwareEngineering #CleanCode #InterviewQuestion
To view or add a comment, sign in
-
-
Today’s focus was on understanding why StringBuilder exists and how it changes the way strings are handled in Java. What changed from the previous learning: - Strings are immutable, so every modification creates a new object and increases memory usage - StringBuilder is mutable, which means changes happen in the same object without creating new ones - Common operations like append, insert, delete, reverse, and setCharAt make real text manipulation much more efficient A simple practice example: StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); // Hello World sb.insert(5, ","); // Hello, World sb.replace(7, 12, "Java"); // Hello, Java sb.delete(5, 6); // Hello Java sb.reverse(); // avaJ olleH This made it clear that performance and memory efficiency are the real reasons StringBuilder is used in real applications. The biggest realization: - Working with strings is not only about syntax - It is about choosing the right structure for efficiency Not perfect yet, but progress is visible, especially in understanding how Java handles text internally. #java #stringbuilder #datastructures #codingjourney #learninginpublic #softwaredevelopment
To view or add a comment, sign in
-
Quick Java Tip 💡: Labeled break (Underrated but Powerful) Most devs know break exits the nearest loop. But what if you want to exit multiple nested loops at once? Java gives you labeled break 👇 outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outer; // exits BOTH loops } } } ✅ Useful when: Breaking out of deeply nested loops Avoiding extra flags/conditions Writing cleaner logic in algorithms ⚠️ Tip: Use it sparingly — great for clarity, bad if overused. Small features like this separate “knows Java syntax” from “understands Java flow control.” #Java #Backend #DSA #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development