Did the == operator look at objects ?
No. It only looked at the two reference variables.
They held different references,
so the ==
evaluated to false.
Here is another example program:
public 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.
Both strA and strB contain the same reference.
So strA == strB evaluates to true.
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 == operator is like comparing phone numbers, but not actually using a phone number to make a call.
The program will output:
The Gingham Dog The Gingham Dog Same info in each reference variable.
How many objects are there in this program? How many reference variables are there?