Java Reference
In-Depth Information
9.
Comment out all the main method statements.
10.
Add the following statement after the main method header:
System.out.println("Joe" == "Joe");
11.
Save and run the application.
The result will be the Boolean value true in the console. This same comparison was done between the different
objects' name values. The Employee name getters returned two identical character strings that were compared and
found to be equal.
Unfortunately, comparing strings gets a little complicated.
Tutorial: Comparisons between String Variables
Now let's try to compare string variables:
1.
Comment out the current main method statement and add the following:
String name1 = new String("Joe");
String name2 = new String("Joe");
System. out .println(name1 == name2);
2. Save the source and run the application.
As you probably expected, the result is false. We compared two String variables that point to two different
String objects (just as we did with the Employee variables earlier).
3.
Comment out the current main method statements, add the following, and run
the application:
String name1 = new String("Joe");
String name2 = name1;
System. out .println(name1 == name2);
This result is true because we set name2 equal to name1. In this case, both String variables point to the
same object.
4.
Comment out the current main method statements, add the following, and run
the application:
String name1 = "Joe";
String name2 = "Joe";
System.out.println(name1 == name2);
This produces the surprising result of true . Using the shorthand notation to define the strings activates a JVM
feature called “string optimization.” Explaining in detail what happens in the first two statements will clarify
“string optimization”.
The first statement does the exact same thing as the first statement in steps 1 and 3: a String object is created and
name1's value is set to the String object's memory location.
The second statement, because it does not explicitly tell the JVM to create a new object, activates “string
optimization.” The JVM searches for any already existing String object that contains the same value (Joe). If there is
an already existing object, the memory address of the already existing object is assigned to name2 (as in step 3).
 
Search WWH ::




Custom Search