📌 new String() vs String Literal in Java In Java, Strings can be created in two different ways. Although they may look similar, they behave differently in memory. 1️⃣ String Literal When a String is created using a literal: • The value is stored in the String Pool • JVM checks if the value already exists • Existing reference is reused if available Example: String s1 = "java"; String s2 = "java"; Both references point to the same object. 2️⃣ new String() When a String is created using the `new` keyword: • A new String object is created in heap memory • It does not reuse the String Pool object by default Example: String s3 = new String("java"); `s3` points to a different object even if the value is the same. 3️⃣ Memory Impact • String literals reduce memory usage through reuse • `new String()` always creates an additional object • Using `new` unnecessarily can increase memory consumption 4️⃣ When to Use • Prefer String literals for most use cases • Use `new String()` only when a distinct object is explicitly required 💡 Key Takeaways: - String literals use the String Pool - `new String()` creates a separate heap object - Understanding this helps write memory-efficient code #Java #CoreJava #String #JVM #BackendDevelopment
Java String Creation Methods: Literal vs new String()
More Relevant Posts
-
🧠 How String Pooling actually works in Java. Most developers know Strings are immutable. Fewer understand why Java aggressively pools them 🔍 Let’s break it down 👇 📦 What is the String Pool? It’s a special memory area inside the Heap 🧠 Used to store unique string literals only. Java’s rule is simple: 👉 Same value → same object ✍️ String literals vs new String() String a = "java"; String b = "java"; ✅ a == b → true Both point to one pooled object But: String c = new String("java"); ❌ New object created Different reference, same value 🔁 How pooling really works When the JVM sees a string literal: 1️⃣ Checks the String Pool 2️⃣ If it exists → reuses it 3️⃣ If not → creates & stores it Zero duplicates and Maximum reuse. ⚡ 💾 Why Java does this String pooling gives: ✅ Lower memory usage ✅ Faster comparisons (== works for literals) ✅ Better cache locality Critical when: 📊 Millions of strings exist 🌐 APIs, configs, logs, JSON keys 🔐 Why immutability matters Strings must be immutable for pooling to be safe 🛡️ If one reference changed the value: 💥 Every reference would break Immutability = thread-safe sharing 🧵 🧪 The intern() method String s = new String("java").intern(); 📌 Forces the string into the pool 📌 Returns the pooled reference 🎯 Final takeaway String pooling is not magic ✨ It’s a memory optimization backed by immutability Once you understand this, Java’s String design makes perfect sense ☕ #Java #JVMInternals #StringPool #MemoryManagement #BackendEngineering
To view or add a comment, sign in
-
-
Why String is a immutable in Java? First, What is string, String ? string -> A string is a sequence of characters placed inside double quotes (" "). Technically, it is called a String literal. e.g -> String s1="Om"; -> "Om" is a string literal. String -> A String is a predefined class in Java. It is used to storing a sequence of characters. e.g. -> String s1="om"; -> it is String declaration Now, the main point: Why is String Immutable?-> In Java, String objects are stored in the String Constant Pool (SCP), which resides inside the Heap memory of the JVM. e.g. -> String s1 = "Om"; String s2 = s1.concat("Shelke"); "Om" is stored in the String Constant Pool. When we try to modify or concatenate the string, a new String object is created. The existing String object is never modified. Every modification creates a new object. This behavior is called immutability. String immutable is made for security, memory optimization, and thread safety purposes. #corejava #javadeveloper
To view or add a comment, sign in
-
-
🔍 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
To view or add a comment, sign in
-
💡 Why does simple string concatenation sometimes slow down Java code?🤔 Because not all strings behave the same behind the scenes. Let’s quickly break down String, StringBuilder and StringBuffer — same purpose, very different behavior. 🔹 String ✅ Immutable. Once created, it cannot change. ✅ Every update creates a new object in memory. ✅ Good for constants and fixed messages. ⚠️ Avoid in loops or repeated concatenations — it’s memory heavy String s = "Hello"; s = s + " Java"; 🔹 StringBuilder ✅ Mutable. Changes the same object. ✅ Much faster and memory-friendly. ✅ Best option for loops and dynamic text. ⚠️ Not thread-safe — avoid in multi-threaded code. StringBuilder sb = new StringBuilder("Hello"); sb.append(" Java"); 🔹 StringBuffer ✅ Mutable and thread-safe. ✅ Safe when multiple threads modify text. ⚠️ Slower than StringBuilder due to synchronization. StringBuffer sb = new StringBuffer("Sync"); sb.append(" Safe"); 🎯 Final takeaway: 👉 Fixed text → String 👉 Speed needed → StringBuilder 👉 Multi-threaded code → StringBuffer #Java #CoreJava #string #JavaInterview #JavaDeveloper #Programming #SoftwareEngineering #BackendDevelopment #CodingInterview
To view or add a comment, sign in
-
📘 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
-
Lambda Expressions vs Anonymous Inner Classes in Java Java didn’t introduce lambdas just to reduce lines of code. It introduced them to change the way we think about behavior. Anonymous Inner Classes (Old way) Runnable r = new Runnable() { @Override public void run() { System.out.println("Running"); } }; ✔ Works ❌ Verbose ❌ Boilerplate-heavy ❌ Focuses more on structure than intent ⸻ Lambda Expressions (Modern Java) Runnable r = () -> System.out.println("Running"); ✔ Concise ✔ Expressive ✔ Focused on what, not how ⸻ Why Lambdas are better 🔹 Less noise, more intent You read the logic, not the ceremony. 🔹 Functional programming support Lambdas work seamlessly with Streams, Optional, and functional interfaces. 🔹 Better readability Especially when passing behavior as a parameter. 🔹 Encourages stateless design Cleaner, safer, more predictable code. ⸻ When Anonymous Inner Classes still make sense ✔ When implementing multiple methods ✔ When you need local state or complex logic ✔ When working with legacy Java (<8) Remember: Lambdas are for behavior, not for stateful objects. ⸻ Bottom line If it’s a single-method interface → use Lambda If it’s complex or stateful → anonymous class is fine Modern Java isn’t about writing clever code. It’s about writing clear, readable, intention-revealing code. #Java #LambdaExpressions #AnonymousClass #CleanCode #ModernJava #SoftwareEngineering #BackendDevelopment #JavaCommunity
To view or add a comment, sign in
-
-
Last week, I wrote an article about Java annotations, in which I mentioned reflection several times. Annotations only become powerful when something reads them. That “something” is usually Java Reflection. Reflection is the ability of a program to inspect and interact with its own structure at runtime: classes, methods, fields, annotations, constructors, and more. In “regular” Java code, everything is known at compile time: - The class. - The available methods. - Exactly what you're calling. You can write code to: - Create an object - Call a method - Get a value This approach is simple, safe, and fast, but also static. The compiler knows everything upfront. Reflection changes that model, making it possible to discover things at runtime: - What class is this object? - What methods does it expose? - What annotations are present? - Can I invoke this method dynamically? Instead of calling a method directly, you ask the runtime if a method exists and how invoke it. This is why reflection is essential for frameworks. Imagine writing a framework that works with any user-defined class: - Controllers - Entities - DTOs - Test classes - Configuration objects You don’t know these classes at compile time. Without reflection, you would be limited to treating everything as Object, with very little behavior beyond toString(). Reflection is what allows frameworks to: - Scan classes and methods - Detect annotations - Instantiate objects dynamically - Inject dependencies - Map HTTP requests to methods - Serialize and deserialize data In short: - Annotations declare intent - Reflection discovers and executes that intent However, reflection should be used carefully. It bypasses some compile-time guarantees. When overused, it can impact performance and make code harder to reason with. But when applied deliberately, particularly in infrastructure and framework code, it enables a level of flexibility that plain Java cannot offer. Reflection is a powerful runtime mechanism, the foundation behind many of the tools Java developers rely on every day. If you’ve ever used Spring, JUnit, Hibernate, or Jackson, you’ve been using reflection all along, whether you realized it or not. If you’re curious, check the examples section in my article on annotations to see reflection in action: https://lnkd.in/dvzkV9rs #Java #Reflection #Framework #Annotations #SoftwareEngineering
To view or add a comment, sign in
-
🧠 var Keyword in Java — Type Inference Explained #️⃣ var keyword in Java Introduced in Java 10, var allows local variable type inference. 👉 The compiler automatically determines the variable type. 🔹 What is var? var lets Java infer the type from the assigned value. Instead of writing: String name = "Vijay"; You can write: var name = "Vijay"; The compiler still treats it as String. 👉 var is NOT dynamic typing 👉 Type is decided at compile-time 🔹 Why was var introduced? Before var: ⚠ Long generic types ⚠ Repeated type declarations ⚠ Verbose code ⚠ Reduced readability Example: Map<String, List<Integer>> data = new HashMap<>(); With var: var data = new HashMap<String, List<Integer>>(); Cleaner and easier to read. 🔹 Rules of using var ✔ Must initialize immediately ✔ Only for local variables ✔ Cannot use without value ✔ Cannot use for fields or method parameters ✔ Type cannot change after assignment Invalid: var x; // ❌ compile error 🔹 Where should we use var? Use var when: ✔ Type is obvious from right side ✔ Long generic types ✔ Stream operations ✔ Loop variables ✔ Temporary variables Avoid when: ❌ It reduces readability ❌ Type becomes unclear 🧩 Real-world examples var list = List.of(1, 2, 3); var stream = list.stream(); var result = stream.map(x -> x * 2).toList(); Perfect for modern functional style. 🎯 Interview Tip If interviewer asks: Is var dynamically typed? Answer: 👉 No. Java is still statically typed. 👉 var only removes repetition. 👉 Type is fixed at compile-time. 🏁 Key Takeaways ✔ Introduced in Java 10 ✔ Local variable type inference ✔ Reduces boilerplate ✔ Improves readability ✔ Not dynamic typing ✔ Use wisely #Java #Java10 #VarKeyword #ModernJava #JavaFeatures #CleanCode #ProgrammingConcepts #BackendDevelopment #JavaDeepDive #TechWithVijay #VFN #vijayfullstacknews
To view or add a comment, sign in
-
-
🧵 Java String Pool vs String Object — What You Need to Know ━━━━━━━━━━━━━━━━━━━━━━ 💡 String literals in Java are treated specially. JVM stores them in a String Pool, making memory usage efficient and comparison fast. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 String Pool (Literal Strings) Memory area inside the Heap for string literals. JVM reuses literals to save memory. Immutable, so safe to share references. String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true → same reference ✅ Multiple references point to the same object in the pool. 🔹 String Objects (new keyword) Created outside the pool in Heap memory. Even if the same content exists in the pool, new always creates a new object. String s3 = new String("Java"); System.out.println(s1 == s3); // false → different object System.out.println(s1.equals(s3)); // true → content matches ✅ Use s3.intern() to add it to the String Pool explicitly. ⚡ Why JVM treats string literals specially Immutable → safe to share references. Memory optimization → only one copy stored. Fast comparison → == works for literals. Key Takeaway: Always prefer string literals for repeated values. Use new String() only when necessary. .intern() can explicitly add objects to the pool. #Java #StringPool #MemoryOptimization #Backend #TechExplained #ProgrammingTips #JVM #Immutable
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. #Java #CoreJava #JVM #JavaMemory #ProgrammingConcepts #SoftwareEngineering #InterviewPrep #DeveloperJourney #LearningEveryDay
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