Testing Strings for Equality

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

Answer:

The filled blanks are below.

Testing Strings for Equality

The if statement skips over cells that contain null. Otherwise, the method tests if cell j of the array refers to a String that matches target. In other words, we want to test if the contents of two Strings are equivalent.

class Searcher
{
  // seek target in the array of strings.
  // return the index where found, or -1 if not found.
  public static int search( String[] array, String target )
  {
     for ( int j=0; j  < array.length; j++ )
       if ( array[j] != null )
         // do something here with a non-null cell

  }
}

class SearchTester
{
  public static void main ( String[] args )
  {
    . . . . . .
    int where = Searcher.search( strArray, "Peoria" );
    . . . . . .
  }
}

QUESTION 18:

Which of the following is true when array[j] and target refer to equivalent Strings?

  • array[ j ] = target
  • array[ j ] == target
  • array[ j ].equals( target )