Did the == operator look at the contents of the objects when the if
statement executed?
Answer:
No. It only looked at the two reference variables.
They held different references,
so the ==
evaluated to false.
Two Reference Variables Pointing to One Object.
Here is another example program:
class EgString5
{
public static void main ( String[] args )
{
String strA; // reference to the object
String strB; // another reference to the object
strA = new String( "The Gingham Dog" ); // Create the only object.
// Save its reference in strA.
System.out.println( strA );
strB = strA; // Copy the reference into strB.
System.out.println( strB );
if ( strA == strB )
System.out.println( "Same info in each reference variable." );
}
}
When this program runs,
only one object is created (by the new).
The unique reference to the object is put into strA.
Then the statement
strB = strA; // Copy the reference to strB.
copies the reference that is in strA into strB.
It
does not make a copy of the object!
Or, saying nearly the same thing: making a copy of a reference to an object
does not make a copy of the object!
The same information is stored in strA and strB.
Both variables refer to the same object.
This is somewhat like giving your phone number to several people:
each copy of your phone number is a reference to you, but there is only one you.
The program will output:
The Gingham Dog The Gingham Dog Same info in each reference variable.
QUESTION 17:
How many objects are there in this program? How many reference variables are there?