The Plain Picture#
A printed name badge. You can't erase the letters. To "change" the name, you print a new badge. And the office keeps a shared tray of badges for common names, so everyone called "Priya" can use the same printed badge instead of printing their own.
The Real Names#
Stringis immutable (Ch 5). Every method that seems to change a string —toUpperCase,replace,substring,+— returns a new String; the original is untouched.The String pool (or string constant pool) is a special area where Java keeps one shared copy of each string literal. Two literals with the same text refer to the same object.
new String("...")deliberately creates a new, separate object outside the pool.intern()returns the pool's copy of a string.
Under the Hood#
Immutability in action#
String s = "hi";
s.toUpperCase(); // creates "HI" ... and throws it away
System.out.println(s); // hi
s = s.toUpperCase(); // keep the new object by re-pointing s
System.out.println(s); // HI== vs equals on strings — finally explained#
String a = "Priya"; // literal → pool
String b = "Priya"; // same literal → the SAME pooled object
String c = new String("Priya"); // a brand-new object
System.out.println(
(a == b) + " " + (a == c) + " " + a.equals(c) + " " + (a == c.intern())
);
// true false true true String pool elsewhere on the heap
a ───┐ ┌───────────────┐ ┌───────────────┐
├─▶ │ "Priya" │ ◀── c.intern() c ──▶ │ "Priya" │ (new String)
b ───┘ └───────────────┘ └───────────────┘==compares references: "same object?" —a == bis true only because of pooling;a == cis false.equalscompares contents: "same text?" — always what you mean.
Strings built at runtime (read from input, built with + in a loop, returned by substring) are generally not pooled, so ==
"works" in small tests with literals and fails in production with real input. Always compare strings with .equals.
(equalsIgnoreCase ignores upper/lower case.)
Why did Java make String immutable?#
Safety: strings are used for file paths, URLs, class names and passwords. If another piece of code could change a string after it was checked, security checks would be meaningless.
Pooling: sharing one object among many variables is only safe if nobody can change it.
Hashing: a String caches its hash code the first time it's computed, which makes it fast as a
HashMapkey — only possible because its contents never change (Collections, From the Inside).Thread safety: immutable objects can be shared between threads with no locking.
String methods you'll use in DSA#
char[] chars = "dcba".toCharArray(); // String → char array (mutable, sortable)
Arrays.sort(chars);
System.out.println(new String(chars)); // abcd ← char array → String
// (sorted letters: the classic anagram key)
"apple".compareTo("banana") // -1 (negative: "apple" comes first in dictionary order)
"b".compareTo("a") // 1 (positive: "b" comes after)
"Priya".equalsIgnoreCase("PRIYA") // true
String.join(", ", List.of("Priya", "Rahul", "Aisha")) // Priya, Rahul, Aisha
s.split(",") s.trim() s.strip() s.replace("a", "b") s.chars() String.valueOf(charArray)compareTo returns a negative number, zero or a positive number — the standard way Java expresses "less than / equal / greater than",
used for sorting (Collections, From the Inside).
Gotchas
==on strings — the #1 Java beginner bug. Useequals.Calling a String method and ignoring the result (
s.trim();) does nothing. Strings never change in place.s.equals(null)is fine;null.equals(s)throws NPE. When comparing to a constant, put the constant first:"admin".equals(role)never throws, even ifroleis null.
Check yourself
5 questionsWhy does a == b print true for two identical literals but false for new String?
Show answerHide answer
Identical literals share one pooled object; new String creates a separate object; == compares object identity.
What does s.replace("a", "b"); on its own line do to s?
Show answerHide answer
Nothing — it returns a new string that is thrown away.
Give three reasons String is immutable.
Show answerHide answer
Security (checked values can't change), safe pooling/sharing, cached hash codes for fast map keys, thread safety.
Why write "admin".equals(role) instead of role.equals("admin")?
Show answerHide answer
It can't throw a NullPointerException if role is null.
How do you sort the letters of a string?
Show answerHide answer
char[] c = s.toCharArray(); Arrays.sort(c); String sorted = new String(c);