Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Classes, Objects and Memory

    Strings, Properly

    String is immutable (Ch 5). Every method that seems to change a string — toUpperCase, replace, substring, + —

    Chapter 6 of 106 min readOften asked in interviews

    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#

    • String is 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#

    Java
    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#

    Java
    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 == b is true only because of pooling; a == c is false.

    • equals compares 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?#

    1. 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.

    2. Pooling: sharing one object among many variables is only safe if nobody can change it.

    3. Hashing: a String caches its hash code the first time it's computed, which makes it fast as a HashMap key — only possible because its contents never change (Collections, From the Inside).

    4. Thread safety: immutable objects can be shared between threads with no locking.

    String methods you'll use in DSA#

    Java
    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. Use equals.

    • 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 if role is null.

    Check yourself

    5 questions
    1

    Why does a == b print true for two identical literals but false for new String?

    Show answer

    Identical literals share one pooled object; new String creates a separate object; == compares object identity.

    2

    What does s.replace("a", "b"); on its own line do to s?

    Show answer

    Nothing — it returns a new string that is thrown away.

    3

    Give three reasons String is immutable.

    Show answer

    Security (checked values can't change), safe pooling/sharing, cached hash codes for fast map keys, thread safety.

    4

    Why write "admin".equals(role) instead of role.equals("admin")?

    Show answer

    It can't throw a NullPointerException if role is null.

    5

    How do you sort the letters of a string?

    Show answer

    char[] c = s.toCharArray(); Arrays.sort(c); String sorted = new String(c);