Java Reference
In-Depth Information
The answer is 2.8. A calculator won't help you on this one. You need to perform the
division longhand to see where the remainder of 2.8 comes from.
The multiplication operators are evaluated left-to-right if the expression does not
contain parentheses. What is the value of result after this statement?
int result = 12 + 2 * 5 % 3 - 15 / 4;
The expression evaluates to an int because all the literal values are int s. Here is how
the expression is evaluated one level of precedence at a time. The parentheses are added for
clarifi cation.
12 + (2 * 5) % 3 - (15 / 4)
12 + (10 % 3) - 3
(12 + 1) - 3
13 - 3
10
Therefore the value of result is 10 after the statement executes.
The Increment and Decrement Operators
The operators ++ and - - are referred to as the increment and decrement operators because
they increment and decrement (respectively) a numeric type by 1. The operators can be
applied to an expression either prefi x or postfi x. These operators have the highest level of
precedence of all the Java operators. They can only be applied to numeric operands, and
the result is the same data type as the operand.
For example, the following statements create an int and increment it using ++ . What is
the output of this code?
3. int x = 6;
4. System.out.println(x++);
5. System.out.println(x);
Adding or subtracting 1 seems simple enough, but these operators can be confusing
because of when they are evaluated! The output of the previous statements is
6
7
When the operator appears after the operand, the increment or decrement does not
occur until after the operand is used in the current expression. On line 3, x is printed out as
6, then incremented to 7, which is demonstrated by the output of line 5.
When the increment operator appears before the operand, the operand is incremented
fi rst, and then the result is used in the current expression. The same is true for the
decrement operator.
Search WWH ::




Custom Search