If you look at
StringBuilder implementations, you can clearly see how they’ve employed immutability. Check out the screenshots I’ve taken below.
Also, there is one fact that stands out when it comes to discussing this topic (which most of the Sri Lankan interviewers miss out to ask): String Interning. There’s an area in the Heap which is called the String Pool. It’s the same as its name suggests: pools let you create content without duplicates, and retrieve them whenever you need. The JVM has the capability to optimize the usages of Strings by utilizing interning, which essentially means that you create only one instance of a string if you initialize it using the literal (e.g.
String name = "Anuradha" ). This heavily optimizes the memory by cutting down duplicate string literals. In contrast, when you use a
StringBuilder , the literals are added into the heap (not the String Pool; at least in JDK 1.7, unless you call
String.intern() method as far as I know).