Page 150 - Introduction to Programming with Java: A Problem Solving Approach
P. 150
116 Chapter 4 Control Statements 4.5 || Logical Operator
Now let’s look at the complement to the “and” operator—the “or” operator. Assume that you have a variable named response that contains (1) a lowercase or uppercase “q” if the user wants to quit or (2) some other character if the user wants to continue. Write a code fragment that prints “Bye” if the user enters either a lowercase or uppercase “q.” Using pseudocode, you’d probably come up with something like this for the critical part of the algorithm:
if response equals “q” or “Q” print “Bye”
Note the “or” in the if statement’s condition. That works fine for pseudocode, where syntax rules are le- nient, but for Java, you must use || for the “or” operation, not “or.” (Note: || is pronounced “or”) To enter the || operator on your computer, look for the vertical bar key on your keyboard and press it twice. Here’s a tentative Java implementation of the desired code fragment:
Scanner stdIn = new Scanner(System.in);
String response;
System.out.print("Enter q or Q: ");
response = stdIn.nextLine();
Apago PDF ⎫Enhanc
if (response == "q" || response == "Q")
{
}
System.out.println("Bye");
⎬ ⎭
Note that the response variable appears twice in the if statement’s condition. That’s necessary because if both sides of an || condition involve the same variable, you must repeat the variable.
The callout indicates that something is wrong. What is it? If you insert this code fragment into a valid program shell, the program compiles and runs. But when a user responds to the prompt by dutifully entering either “q” or “Q,” nothing happens. The program does not print “Bye.” Why not? Should we have used in- terior parentheses in the “if” condition? Figure 4.6 shows that the == operator has a higher precedence than the || operator, so what we did was OK. The problem is something else.
Don’t Use == to Compare Strings
The problem is with the response
== "q" and response
== "q" expression. The response string variable and the “q” string literal both hold
the response
memory addresses that point to string objects; they don’t hold string objects themselves. So when you use ==, you’re comparing the memory addresses stored in the response string variable and the “q” string literal. If the response string variable and the “q” string literal contain different memory addresses (i.e., they point to different string objects), then the comparison evaluates to false, even if both string objects contain the same sequence of characters. The following picture shows what we’re talking about. The arrows
represent memory addresses. Since they point to two different objects, response false.
== "q" evaluates to
er
When inserted in a main method, this compiles, but it does not “work”!
== "Q" expressions. We’ll focus on