String equality

A little pre-knowledge before we get to the Strings unit.

String is a reference type

Just like arrays, and all other non-primitive types, String is a reference type.

That means that the actual data that makes up the object lives somewhere in memory.

And what we store in a variable or pass as arguments is a reference to that location in memory.

Different Strings are not ==

Just like I can take two pieces of paper and write the same word on both of them, I can make two String objects that live in different places in memory but which contain the same text.

String s1 = new String("foobar");
String s2 = new String("foobar");

These are two different objects. And s1 and s2 are different references.

Thus s1 == s2 is false.

String equality

But if we want to know if two string contain the same text, there’s a method on String objects to check that.

s1.equals(s2) will be true since the two string contain the same text.

The one time you use ==

If we have a String variable that could be null we need to check with ==.

s1.equals("foo") will throw a NullPointerException if s1 is null.

Use short circuiting to check for null then check equals.

s1 != null && s1.equals("whatever");

Two Strings, same text

String s1 = "quux"
String s2 = new String("quux");
String s3 = s2;

Allocate a String object: the object itself, and the array holding its characters.

Store the reference in s1.

Allocate a second String with the same text, somewhere else in memory.

Store that reference in s2. Two objects, two references: s1 != s2 but s1.equals(s2).

Assign the refererence from s2 to s3. s3 == s2 because they reference the same address in memory.

Drawn by the content build (build/memory-diagrams.ts) from the <code visualization="same-text"> block in materials/slides/java/string-equality/slides.deck String length: 4 'q' 'u' 'u' 'x' s1 String length: 4 'q' 'u' 'u' 'x' s2 s3