Lesson Completion
Back to course

Introduction to Strings: Immutable Text in Java

Beginner
15 minutes4.6Java

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

In a Nutshell: Strings are immutable sequences of characters. Once created, a String cannot be modified—any "change" creates a new String object. This design enables thread-safety and optimization.

When Twitter stores your tweets: the text is immutable—edits create new versions, originals are preserved for history!


2. Conceptual Clarity

💡 The Analogy: Engraved Stone Tablets

  • String = Stone tablet with engraved text
  • Immutable = Can't erase the engraving
  • "Modify" = Carve a new tablet instead
  • Advantage = Tablets can be safely shared (no one can alter your copy)
graph LR Create["String s = 'Hello'"] --> Pool["String Pool"] Modify["s = s + ' World'"] --> NewString["New String 'Hello World'"] Pool --> Still["'Hello' still exists"] style Pool fill:#2E7D32 style NewString fill:#F57C00

3. Technical Mastery

Why Immutability?

BenefitExplanation
Thread-safetySafe to share across threads without synchronization
SecurityPrevents tampering (passwords, URLs, class names)
CachingString pool reuses literals, saves memory
Hash cachinghashCode computed once, cached forever

How It Works

java
String s1 = "Hello"; // Points to pool String s2 = "Hello"; // Same pool object String s3 = s1 + " World"; // NEW object created System.out.println(s1 == s2); // true (same reference) System.out.println(s1 == s3); // false (different objects)

4. Interactive & Applied Code

java
public class StringIntro { public static void main(String[] args) { // Strings are objects String greeting = "Hello, World!"; System.out.println(greeting.length()); // 13 // Immutability demonstration String original = "Java"; String modified = original.concat(" Programming"); System.out.println(original); // "Java" (unchanged!) System.out.println(modified); // "Java Programming" // String as character sequence String text = "Coffee"; char first = text.charAt(0); // 'C' char last = text.charAt(5); // 'e' // Strings from char array char[] letters = {'H', 'i'}; String hiString = new String(letters); // "Hi" // String methods return NEW strings String upper = "hello".toUpperCase(); // "HELLO" String lower = "WORLD".toLowerCase(); // "world" // Original literals unchanged String literal = "immutable"; literal.toUpperCase(); // Creates new String, but... System.out.println(literal); // Still "immutable"! // Must reassign to "keep" changes literal = literal.toUpperCase(); System.out.println(literal); // Now "IMMUTABLE" } }

⚠️ Common Mistakes

Mistake #1: Forgetting methods return new Strings

java
String s = "hello"; s.toUpperCase(); // ❌ Discarded! s still "hello" s = s.toUpperCase(); // ✅ Reassign

Mistake #2: Concatenation in loops (O(N²))

java
String result = ""; for (int i = 0; i < 1000; i++) { result += i; // ❌ Creates 1000 new Strings! } // Use StringBuilder instead

Mistake #3: Comparing with ==

java
String a = new String("test"); String b = new String("test"); System.out.println(a == b); // false (different objects!) System.out.println(a.equals(b)); // true ✅

5. The "Interview Corner"

🏆 Q1: "Why are Strings immutable in Java?" Answer: Security (class loading, network connections use strings), Thread-safety (no synchronization needed), Caching (String pool optimization), Hash code caching (for HashMap keys).

🏆 Q2: "What's the String Pool?" Answer: Special memory area in heap storing unique string literals. When you write "hello", JVM checks pool first—if exists, returns reference; otherwise creates and adds.

🏆 Q3: "How to make String mutable in Java?" Answer: You can't—but use StringBuilder or StringBuffer for mutable character sequences.


🎓 Key Takeaways

✅ Strings are immutable—cannot be changed after creation
✅ All modification methods return new String objects
✅ String pool enables memory optimization
✅ Use equals() for comparison, not ==
✅ Use StringBuilder for efficient concatenation in loops

Topics Covered

Java FundamentalsStrings

Tags

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

Last Updated

2025-02-01