Linear Search

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:

Yes, of course. In fact, it can be simplified.

Linear Search

Linear search can be simplified if it does not have to test each array entry for null. Here is some code with search() partially finished:

class PhoneEntry
{
  String name;    // name of a person
  String phone;   // their phone number
 
  . . . . . 
}

class PhoneBook
{ 
  PhoneEntry[] phoneBook; 

  PhoneBook()    // constructor
  {
    phoneBook = new PhoneEntry[ 5 ] ;

    . . . . . .
  }

  PhoneEntry search( String targetName )  
  {
    // use linear search to find the targetName

    for ( int j=0; j < phoneBook.; j++ )
    {
      if ( phoneBook[ j ].name.equals(  ) )
        return phoneBook[ j ];
    }

    return null;
  }
}

Recall that search() returns either a reference to the correct entry, or null if the entry could not be found.

QUESTION 24:

Complete the search() method.