go to previous page   go to home page   go to next page highlighting
    String stringG = "Red Delicious" ;
    String stringH = "Red Delicious" ;

    if (stringG==stringH)
      System.out.println( "One Literal" );
    else
      System.out.println( "NOT Equal" );         

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?


go to previous page   go to home page   go to next page