String immutability, the String Pool, StringBuilder/StringBuffer, and common String methods.
Question 1: Why is the String class immutable in Java?
Ans
Once a String object is created, its internal character content can never be changed — any operation that looks like it modifies a String, such as concatenation, actually creates and returns a brand-new String object. Immutability makes strings safe to share across threads without synchronization, allows the JVM to cache each String's hash code, and makes String pooling possible.
Example
java
String s = "Java";
s.concat(" 17");
System.out.println(s); // still prints "Java" — concat() returned a new String that was discarded
Important Point
To keep a changed value, you must assign the returned String back, e.g. s = s.concat(" 17").
Question 2: What is the String Pool, and how does it save memory?
Ans
The String Pool is a special JVM-managed memory area that stores string literals so that identical literals can share the same underlying object instead of each creating a separate one. When you write a String literal, Java checks the pool first and reuses an existing matching object if one is already there.
Example
java
String a = "Java";
String b = "Java";
System.out.println(a == b); // true — both point to the same pooled object
Important Point
Strings created with new String("Java") are NOT automatically pooled — they create a separate object on the heap even if an identical literal is in the pool.
Question 3: What's the difference between == and equals() for Strings?
Ans
== compares whether two references point to the exact same object in memory, reference identity, while .equals(), overridden by String, compares the actual sequence of characters, returning true whenever the content matches regardless of whether they're the same object.
Example
java
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b); // false — two different objects
System.out.println(a.equals(b)); // true — same characters
Important Point
Always use .equals() to compare String content — using == is a very common beginner bug.
Question 4: What is the difference between String, StringBuilder, and StringBuffer?
Ans
String is immutable, so every modification creates a new object. StringBuilder is mutable and lets you change the same object's content in place, which is much more efficient for building or editing strings repeatedly in a single thread. StringBuffer behaves like StringBuilder but has synchronized methods, making it safe for multiple threads at the cost of extra overhead.
Example
java
StringBuilder sb = new StringBuilder();
sb.append("Java").append(" ").append("Interview");
System.out.println(sb); // "Java Interview" — same object modified in place
Important Point
For loops that build a large string, always prefer StringBuilder over repeated String concatenation, since each += on a String creates a whole new object.