Reference Comparison
The == operator compares the values in variables.
- With primitives:
int x = 17;
int y = 17;
int z = 42;
System.out.println(x == y); // true
System.out.println(x == z); // false
- With references:
String c = new String("cat"); // A new object on the heap
String d = new String("cat"); // Another new String object
System.out.println(c == d); // false
// The references to the two Strings are different
We've learned that to compare the actual contents of two String objects, we use equals().
System.out.println(c.equals(d)); // true
The String class provides the equals() method to allow comparison of the contents of two Strings instead of the references in two String variables.
Practice Exercise¶
The String Pool¶
The
Stringclass is special, in that we can create aStringobject just by putting a double-quoted literal in our code.When we create strings this way, Java first checks to see if there's already a
Stringwith the exact same content in a special region of memory called the String Pool. If it finds one, then instead of creating a newStringJava returns the reference to the existingStringin the String Pool.When we useString s1 = "cat"; String s2 = "cat"; // There's already a "cat" in the String Pool System.out.println(s1 == s2); // truenewto create aString, then Java ignores the String Pool and creates a new object on the heap.String c = new String("cat"); // A new object on the heap String d = new String("cat"); // Another new String object System.out.println(c == d); // false // The references to the two Strings are different