Picture of One Objects and Two Reference Variables

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

How many objects are there in this program? How many reference variables are there?

Answer:

There is one object (after the new operator has worked) and there are two reference variables.

Picture of One Objects and Two Reference Variables

Here is a picture showing the situation in the new program:

Now when the expression strA == strB is evaluated, it is true because the contents of strA and of strB are the same (they both contain the same reference).


    String strA;  // will contain the reference to the object
    String strB;  // another copy of the reference to the object
     
    strA = new String( "The Gingham Dog" ); 
    System.out.println( strA   ); 

    strB = strA;
    System.out.println( strB   );

    if ( strA == strB )
      System.out.println( "Same info in each reference variable." );  

When two reference variables refer to the same object, the == operator will evaluate to true.

QUESTION 18:

In the new program, did the == operator look at the contents of the object?