String References and Immutability
Something that is immutable means that it cannot be changed. One immutable thing in this universe is a Java String, which means, after it is assigned a value, that value never changes—ever. To which you might reply, “Oh yeah? Well what about this?” and then whip out some ninja code like this:
String s = "kitty"; s = s.concat(" cat"); System.out.println(s); //prints kitty cat
The concat method of the String class takes the string value of the object on which you call the method and concatenates (adds to the end) the literal parameter you pass the method. So that looks like all kinds of mutability, right?
Here's what really happens:
When we call concat, the virtual machine takes the value of the String s, and ...
Get Java Garage 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.