Common Array Algorithms

23. equals Method


Answer:

One Literal 

Recall that, as an optimization, only one object is made for string literals containing the same characters. So in the above,
both variables point to the same object. The == returns true because stringG and stringH contain identical references.

equals Method

Here is another touchy situation:

 
class ArrayEquality
{
  public static void main ( String[] args )
  {
    int[] arrayE = { 1, 2, 3, 4 };
    int[] arrayF = { 1, 2, 3, 4 };
    
    if (arrayE.equals( arrayF ) )
      System.out.println( "Equal" );
    else
      System.out.println( "NOT Equal" );      
  }
}

Output:
NOT Equal

The equals() method for arrays returns the same boolean value as does ==.

Question 23:

Are there times when you would like a method that examines two arrays (like the above two) and returns true or false depending on the elements of the array?