Java Reference
In-Depth Information
Suppose you have three integer variables:
num1
,
num2
, and
minNum
. You want to assign
minNum
the minimum of
num1
and
num2
. You can use ternary operator to accomplish this.
int num1 = 50;
int num2 = 25;
// Assigns num2 to minNum, because num2 is less than num1
int minNum = (num1 < num2 ? num1 : num2);
Operator Precedence
Consider the following piece of code:
int result;
result = 10 + 8 / 2; // What will be the value assigned to result?
What will be the value assigned to the variable
result
after the last statement in this piece of code is executed?
Will it be
9
or
14
? It depends on the operation that is done first. It will be
9
if the addition
10 + 8
is performed first.
It will be
14
if the division
8/2
is performed first. All expressions in Java are evaluated according to operator precedence
hierarchy, which establishes the rules that govern the order in which expressions are evaluated. Operators with higher
precedence are evaluated before the operators with lower precedence. If operators have the same precedence, the
expression is evaluated from left to right. Multiplication, division, and remainder operators have higher precedence
than addition and subtraction operators. Therefore, in the above expression,
8/2
is evaluated first, which reduces the
expression to
10 + 4
, which in turn results in
14
.
Consider another expression.
result = 10 * 5 / 2;
The expression,
10 * 5 / 2
, uses two operators: a multiplication operator and a division operator. Both operators
have the same precedence. The expression is evaluated from left to right. First, the expression
10 * 5
is evaluated, and
then the expression
50 / 2
is evaluated. The whole expression evaluates to
25
. If you wanted to perform division first,
you must use parentheses. Parentheses have the highest precedence, and therefore, the expression within parentheses
is evaluated first. You can rewrite the above piece of code using parentheses.
result = 10 * (5 / 2); // Assigns 20 to result. Why?
You can also use nested parentheses. In nested parentheses, the innermost parentheses' expression is evaluated
first. Table
4-6
lists Java operators in their precedence order. Operators in the same level have the same precedence.
Table
4-6
lists some of the operators I have not discussed yet. I will discuss them later in this chapter or in other
chapters. In the table, a lower the value in the level column indicates a higher precedence.