Strings as Objects

Here's an interesting excercise regarding references in Java.

String s = "blah";
String t = "blah";

System.out.println(s == t);

s = t;

System.out.println(s == t);

This prints:
true
true

to the screen. Now try:

String s = new String("blah");
String t = new String("blah");

System.out.println(s == t);

s = t;

System.out.println(s == t);

This prints
false
true

to the screen. Java recognizes that the contents of the two string literals are identical and reuses the object by referencing both s and t to it. The "new" operator in the second listing, however forces Java to create two distinct objects.

| Last updated on

Comments