Java Reference
In-Depth Information
APPENDIX
C
Operators
C.1
Arithmetic expressions
Java has a considerable number of operators available for both arithmetic and logical expressions.
Table C.1 shows everything that is classified as an operator, including things such as type casting and
parameter passing. Most of the operators are either binary operators (taking a left and a right operand)
or unary operators (taking a single operand). The main binary arithmetic operations are:
addition
+
subtraction
multiplication
*
division
/
modulus , or remainder after division
%
The results of both division and modulus operations depend on whether their operands are inte-
gers or floating-point values. Between two integer values, division yields an integer result and
discards any remainder, but between floating-point values, a floating-point value is the result:
5 / 3 gives a result of 1
5.0 / 3 gives a result of 1.6666666666666667
(Note that only one of the operands needs to be of a floating-point type to produce a floating-
point result.)
When more than one operator appears in an expression, then rules of precedence have to be
used to work out the order of application. In Table C.1, those operators having the highest
precedence appear at the top, so we can see that multiplication, division, and modulus all take
precedence over addition and subtraction, for instance. This means that both of the following
examples give the result 100 :
51 * 3 - 53
154 — 2 * 27
Binary operators with the same precedence level are evaluated from left to right, and unary
operators with the same precedence level are evaluated right to left.
When it is necessary to alter the normal order of evaluation, parentheses can be used. So both of
the following examples give the result 100 :
(205 — 5) / 2
2 * (47 + 3)
 
 
Search WWH ::




Custom Search