O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required