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


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 )  // two different objects; this is false
      System.out.println( "This will not print.");
  }

}

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.

In the 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. There are two objects, made out of two separate sections of main memory, so 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?