Java Reference
In-Depth Information
Continued from previous page
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else { // score < 60
grade = "F";
}
You don't need to set grade to "no grade" now because the compiler can
see that no matter what path is followed, the variable grade will be assigned a
value (exactly one of the branches will be executed).
Object Equality
You saw earlier in the chapter that you can use the == and != operators to test for
equality and nonequality of primitive data, respectively. Unfortunately, these opera-
tors do not work the way you might expect when you test for equality of objects like
strings. You will have to learn a new way to test objects for equality.
For example, you might write code like the following to read a token from the
console and to call one of two different methods depending on whether the user
responded with “yes” or “no.” If the user types neither word, this code is supposed to
print an error message:
System.out.print("yes or no? ");
String s = console.next();
if (s == "yes") {
processYes();
} else if (s == "no") {
processNo();
} else {
System.out.println("You didn't type yes or no");
}
Unfortunately, this code does not work. No matter what the user enters, this program
always prints “You didn't type yes or no.” We will explore in detail in Chapter 8 why
this code doesn't work. For now the important thing to know is that Java provides a
second way of testing for equality that is intended for use with objects. Every Java
object has a method called equals that takes another object as an argument. You can
use this method to ask an object whether it equals another object. For example, we
can fix the previous code as follows:
System.out.print("yes or no? ");
String s = console.next();
 
Search WWH ::




Custom Search