Java Reference
In-Depth Information
As you can see from these examples, conditional expressions enable you to write short and
concise code.
Note
The symbols ? and : appear together in a conditional expression. They form a
conditional operator and also called a ternary operator because it uses three operands.
It is the only ternary operator in Java.
conditional operator
ternary operator
3.33
Suppose that, when you run the following program, you enter the input 2 3 6 from
the console. What is the output?
Check
Point
public class Test {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
System.out.println((x < y && y < z) ? "sorted" : "not sorted" );
}
}
3.34
Rewrite the following if statements using the conditional operator.
if (ages >= 16 )
ticketPrice = 20 ;
else
ticketPrice = 10 ;
3.35
Rewrite the following conditional expressions using if-else statements.
a. score = (x > 10 ) ? 3 * scale : 4 * scale;
b. tax = (income > 10000 ) ? income * 0.2 : income * 0.17 + 1000 ;
c. System.out.println((number % 3 == 0 ) ? i : j);
3.36
Write conditional expression that returns -1 or 1 randomly.
3.15 Operator Precedence and Associativity
Operator precedence and associativity determine the order in which operators are
evaluated.
Key
Point
Section  2.11 introduced operator precedence involving arithmetic operators. This section
discusses operator precedence in more detail. Suppose that you have this expression:
3 + 4 * 4 > 5 * ( 4 + 3 ) - 1 && ( 4 - 3 > 5 )
What is its value? What is the execution order of the operators?
The expression within parentheses is evaluated first. (Parentheses can be nested, in which
case the expression within the inner parentheses is executed first.) When evaluating an expres-
sion without parentheses, the operators are applied according to the precedence rule and the
associativity rule.
The precedence rule defines precedence for operators, as shown in Table 3.8, which con-
tains the operators you have learned so far. Operators are listed in decreasing order of prec-
edence from top to bottom. The logical operators have lower precedence than the relational
operators and the relational operators have lower precedence than the arithmetic operators.
Operators with the same precedence appear in the same group. (See Appendix C, Operator
Precedence Chart , for a complete list of Java operators and their precedence.)
operator precedence
 
 
 
Search WWH ::




Custom Search