Yes. In the first expression, the String pointed to by targetName runs its equals() method;
in the second expression, the String pointed to by phoneBook[j] runs its equals() method.
But if the two Strings are equal, the results will be the same.
Here is the complete program. There are lots of details here, and it is easy to get lost. The cure for this is to run the program and to play with it for a while. Add a few more entries. Search for a name that is not there. The Programming Exercises of this chapter have some suggestions.
If you are running Java from the command line, copy the entire code below to a file PhoneBookTester.java and compile it with javac. If you are using an IDE (like BlueJ) create a separate file for each of the classes.
class PhoneEntry
{
private String name; // name of a person
private String phone; // their phone number
public PhoneEntry( String n, String p )
{
name = n; phone = p;
}
public String getName() {return name;}
public String getPhone() {return phone;}
}
class PhoneBook
{
private PhoneEntry[] phoneBook;
public PhoneBook() // constructor
{
phoneBook = new PhoneEntry[ 5 ] ;
phoneBook[0] = new PhoneEntry( "James Barclay", "(418) 665-1223" );
phoneBook[1] = new PhoneEntry( "Grace Dunbar", "(860) 399-3044" );
//phoneBook[2] = new PhoneEntry( "Paul Kratides", "(815) 439-9271" );
phoneBook[3] = new PhoneEntry( "Violet Smith", "(312) 223-1937" );
phoneBook[4] = new PhoneEntry( "John Wood", "(913) 883-2874" );
}
public PhoneEntry search( String targetName )
{
for ( int j=0; j < phoneBook.length; j++ )
{
if ( phoneBook[ j] != null && phoneBook[ j ].getName().equals( targetName ) )
return phoneBook[ j ];
}
return null;
}
}
public class PhoneBookTester
{
public static void main ( String[] args )
{
PhoneBook pb = new PhoneBook();
// search for "Violet Smith"
PhoneEntry entry = pb.search( "Violet Smith" );
if ( entry != null )
System.out.println( entry.getName() + ": " + entry.getPhone() );
else
System.out.println("Name not found" );
}
}
In this program, must the target String exactly match the String in
the phone book?