Page 483 - Introduction to Programming with Java: A Problem Solving Approach
P. 483
(2>5) ? 2 : 5
⇒ ⇒
(false) ? 2 : 5
5
Using the Conditional Operator
A conditional operator expression cannot appear on a line by itself because it is not a complete statement. It is just part of a statement—an expression. The following code fragment includes two examples of embedded conditional operator expressions:
int score = 58;
boolean extraCredit = true;
score += (extraCredit ? 2 : 0);
System.out.println(
"grade = " + ((score>=60) ? "pass" : "fail"));
How does it work? Since extraCredit is true, the first conditional operator evaluates to 2. score then increments by 2 from its initial value of 58 to 60. Since (score>=60) evaluates to true, the second con- ditional operator evaluates to “pass”. The println statement then prints:
grade = pass
In the above code fragment, we like the parentheses the way they are shown, but in the interest of honing
your debugging skills, let’s examine what happens if you omit each of the pairs of parentheses. As shown in
Appendix 2’s operator precedence table, the conditional operator has higher precedence than the += opera- Apago PDF Enhancer
tor. Therefore, it would be legal to omit the parentheses in the += assignment statement. In the println statement, the conditional operator has lower precedence than the + operator, so you must keep the paren- theses that surround the conditional operator expression. Since the >= operator has higher precedence than the conditional operator, it would be legal to omit the parentheses that surround the score>=60 condition. Note how we omit spaces in the score>=60 condition but include spaces around the ? and : that separate the three components of the conditional operator expression. This style improves readability.
You can use the conditional operator to avoid if statements. Conditional operator code might look more efficient than if statement code because the source code is shorter, but the generated bytecode is typi- cally longer. This is another example of something you might see in someone else’s code, but because it’s relatively hard to understand, we recommend that you use it with restraint in your own code. For example, the score += (extraCredit ? 2 : 0); statement in the above code fragment is rather cryptic. It would be better style to increment the score variable like this:
if (extraCredit)
{
}
score += 2;
11.8 Expression Evaluation Review
So far in this chapter, you’ve learned quite a few type details and operator details. Learn- ing such details will help you debug code that has problems, and it will help you avoid problems in the first place. To make sure that you really understand the details, let’s do some expression evaluation practice problems.
Hand calculation helps you understand.
11.8 Expression Evaluation Review 449