String immutability

One cannot change the String type value assigned to a variable without changing the reference. There are several reasons why JVM authors decided to do that:

  • All String literals are stored in the same common memory area, called string pool. Before a new String literal is stored, the JVM checks whether such a literal is already stored there. If such an object exists already, a new object is not created and the reference to the existing object is returned as the reference to a new object. The following code demonstrates this situation:
        System.out.println("s1" == "s1");        System.out.println("s1" == "s2");        String s1 = "s1";        System.out.println(s1 == "s1");        System.out.println(s1 == "s2");        String s2 = "s1";        System.out.println(s1 ...

Get Introduction to Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.