The equals() Method

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        

Say that itemA == itemB and that itemB == itemC. How many objects are there?

Answer:

Just one object (and three reference variables, each referring to it.)

The equals() Method

The equals( String ) method of class String tests if two Strings contain the same characters.

The equals( String ) method looks at objects. It detects equivalence. The == operator detects identity. For example,

String strA;  // first object
String strB;  // second object
 
strA   = new String( "The Gingham Dog" );   
strB   = new String( "The Gingham Dog" );   

// check for equivalence
if ( strA.equals( strB  )  ) 
  System.out.println( "This WILL print.");

// check for identity
if ( strA  ==  strB ) 
  System.out.println( "This will NOT print.");

In this example, there are two objects. Each object has its own identity, and its own unique reference, so == returns false. Each object contains equivalent data, so equals() returns true.

QUESTION 22:

two photocopies

If you made a photocopy of a sheet of paper, you would have two sheets of paper.

  1. Are the sheets of paper separatate objects?
  2. Is the first sheet == the second sheet?
  3. Is the data on each sheet the same as on the other?
  4. Is the first sheet equals() to the second sheet?