One of the fundamental data types in Java is the String. In fact, it’s used so often that most people don’t even think much about what a String is or how it works. But a String Object works like no other object in Java in two important ways; immutability and internment.

You Can’t Touch This

Immutability means that an object can’t be changed. Ever. You can’t modify any of its values in any way.

While this might not sound very useful, it actually allows Java to optimize how it handles Strings – which is important since they’re used so much in the language – and brings a sense of security to using Strings. As we saw last week, when Objects are changeable, weird side effects can pop up when one variable changes an Object and all the other variables see the change and don’t know what happened.

Strings sidestep this issue by never allowing you to change a String in place. In programming parlance, this means Strings never have side effects. So in this operation:

String a = "hello";
String b = a;

b = b.toUpperCase();

a and b are now pointing to two different String Objects. a is pointing to the original String of "hello" while b is pointing to a copy that’s all uppercase of "HELLO" . Even though a and b were pointing to the same String originally, the method toUpperCase() makes a copy and assigns the copy to b . This leaves a untouched.1

This property allows Strings to do another cool trick. They can Intern.

Lowly Paid College Students?

Interning is a method where you cache objects in memory to speed up creation of those objects. What that means is, all String literals are interned, and if you define the same literal, it will actually be the same Object. A little illustration:

String a = "hello";
String b = "hello";

It looks like a and b are pointing to two different Objects, but they’re not. Here’s why.

When Java sees the "hello" for variable a , it creates a new String Object with the value and assigns the reference to a . It then saves that Object in a table in memory, also called interning.

Then Java sees that b is getting a String with the value "hello" . It checks it’s intern table and sees it already has that Object created. Since Strings can’t be changed, it doesn’t hurt to just give that Object reference to b too, and so it does. Even though the programmer didn’t explicitly say so, a and b are now pointing to the same Object in memory.

In fact, Java is so good at this, it’ll assign to same Object to these variables too:

String c = "hel" +
String d = "h" + "e" + "l" + "l" + "o";

String is the only Class in Java that does interning in the JVM.

Next week we’ll talk about how to use this knowledge to build better programs. (Hint: it has to do with memory management.)

  1. Strings aren’t the only Objects that do this in Java. Can you think of any others? [return]