Next: Example. Up: Strings. Previous: String-related methods.


Equality testing

Textbook: Section 4.1 (p 131)

Last time we spoke about assignments with objects, and how when you assign an object to a variable, you are really copying a reference into the variable, not copying the object itself. As a result, you can have two variables copied into the same object.

This has important consequences when you want to compare two object values: You are comparing references, not the objects themselves. You might be tempted to write the following.

String name = IO.readLine();
if(name == "Carl") IO.println("Hello, professor"); // bad!!
This won't do what you want, however. Even if the user types ``Carl'', the program points name to a new String object containing the word Carl; this will be a different object than the other String object created by the double-quotes, which happens to contain the word Carl also. As a result, ``Hello, professor'' won't be printed.

The answer is to use the equals() method. This is defined for String objects to compare the letters of the string (not the references to the objects). So we should have written the above as:

String name = IO.readLine();
if(name.equals("Carl")) IO.println("Hello, professor");


Next: Example. Up: Strings. Previous: String-related methods.