Two Objects with Equivalent Contents

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        

Could two different objects contain equivalent data?

Answer:

Yes. The objects would be constructed out of different bytes in memory, but would contain equivalent values.

Two Objects with Equivalent Contents

Recall that objects have identity, state, and behavior. "Identity" means that each object is a unique entity, no matter how similar it is to another. Here is a program that shows this situation:


class EgString6
{
  public static void main ( String[] args )
  {
    String strA;  // reference to the first object
    String strB;  // reference to the second object
     
    strA   = new String( "The Gingham Dog" );   // create the first object.  
                                                // Save its reference
    System.out.println( strA ); 

    strB   = new String( "The Gingham Dog" );   // create the second object.  
                                                // Save its reference
    System.out.println( strB );

    if ( strA == strB ) 
      System.out.println( "This will not print.");
  }

}

In this program, there are two objects, each a unique entity. Each object happens to contain data equivalent to that in the other. Each object consists of a section of main memory separate from the memory that makes up the other object. The variable strA contains a reference to the first object, and the variable strB contains a reference to the second object.

Since the information in strA is different from the information in strB,

( strA ==  strB ) 

is false, just as it was in a previous program where there were two objects. Since there are two objects, made out of two separate sections of main memory, the reference stored in strA is different from the reference in strB. It doesn't matter that the data inside the objects looks the same.

QUESTION 20:

What will this example program print to the monitor?