Lesson Completion
Back to course

Creating Strings: Literals, new, and the String Pool

Beginner
15 minutes4.9Java

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: Strings can be created two ways: literals ("hello") use the String Pool for memory optimization, while new creates fresh objects on the heap. Understanding this affects performance and comparisons.

When WhatsApp stores common phrases like "Ok" across millions of chats—the String Pool means one copy serves everyone!


2. Conceptual Clarity

String Pool vs Heap

graph TB subgraph Heap["Heap Memory"] Pool["String Pool"] Regular["Regular Objects"] end Literal["String s1 = 'Hello'"] --> Pool New["String s2 = new String('Hello')"] --> Regular style Pool fill:#2E7D32 style Regular fill:#F57C00

3. Technical Mastery

Creation MethodLocationPooled?Performance
"literal"String Pool✅ Yes✅ Fast
new String("...")Heap❌ No⚠️ Slower
.intern()String Pool✅ Forces✅ Fast

4. Interactive & Applied Code

java
public class CreatingStrings { public static void main(String[] args) { // === STRING LITERALS (Pool) === String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1 == s2); // true (same pool object) // === new KEYWORD (Heap) === String s3 = new String("Hello"); String s4 = new String("Hello"); System.out.println(s3 == s4); // false (different objects) System.out.println(s1 == s3); // false (pool vs heap) // But content is equal System.out.println(s1.equals(s3)); // true ✅ // === INTERN METHOD === String s5 = s3.intern(); // Get pool reference System.out.println(s1 == s5); // true (both from pool) // === FROM CHAR ARRAY === char[] chars = {'J', 'a', 'v', 'a'}; String fromChars = new String(chars); // === FROM BYTE ARRAY === byte[] bytes = {72, 105}; // "Hi" in ASCII String fromBytes = new String(bytes); // === FROM STRINGBUILDER === StringBuilder sb = new StringBuilder("Build"); String fromBuilder = sb.toString(); // === CONCATENATION CREATES NEW === String a = "Hello"; String b = " World"; String c = a + b; // New String object String d = "Hello World"; // From pool System.out.println(c == d); // false (c not pooled at runtime) // COMPILE-TIME CONSTANTS ARE POOLED String e = "Hello" + " World"; // Compiler optimizes to pool System.out.println(d == e); // true! } }

⚠️ Common Mistakes

Mistake #1: Using new unnecessarily

java
String s = new String("text"); // ❌ Creates extra object String s = "text"; // ✅ Use pool

Mistake #2: Comparing with == after new

java
String a = new String("test"); String b = "test"; if (a == b) { } // ❌ false! Use equals()

5. The "Interview Corner"

🏆 Q1: "How many objects created by String s = new String("Hello")?" Answer: Up to 2: One in pool (if "Hello" not already there), one on heap (from new). If "Hello" exists in pool, just 1 new heap object.

🏆 Q2: "What does intern() do?" Answer: Returns the pool reference for equal string. If not in pool, adds it. Useful for memory optimization with many duplicate strings.

🏆 Q3: "Why "a" + "b" == "ab" is true but s1 + s2 == "ab" is false?" Answer: Compile-time constants are concatenated at compile time and pooled. Runtime concatenation creates new heap objects.


🎓 Key Takeaways

✅ Literals use String Pool (memory efficient)
new String() always creates heap object
✅ Use equals() for content comparison
intern() returns pool reference
✅ Compile-time constants are optimized

Topics Covered

Java FundamentalsStrings

Tags

#java#strings#string-manipulation#string-methods#beginner-friendly

Last Updated

2025-02-01