Java Reference
In-Depth Information
tableĀ 2-8: Arithmetic Operators
arithmetic oper ator
ex ample
meaning
result
4+2
Addition
6
+
4-2
Subtraction
2
-
4*2
Multiplication
8
*
4/2
Division
2
/
8%3
Modulo (remainder after integer division)
2
%
Most of these operators are probably very familiar to you already. Addition, subtraction, multiplica-
tion, and division are used in everyday calculations. It is worth noting at this point that while they
operate in the way you understand and expect, the answer is not always exactly what you're looking
for. In other cases, the way data is stored as binary numbers cannot accurately represent non-whole
numbers. For this reason, operations on floating point numbers often result in a number that's very
close to what you expect, but with several digits after the decimal point. This is simply due to the
fact that these decimals are approximations. For example, if you multiply 1.3 times 0.01, the answer
would be 0.013. However, when you ask Java to calculate 1.3f*0.01f, the result is 0.12999999. Of
course, this rounds to the 0.013 you are expecting, so the operation is the same.
Sometimes the problem is not with rounding, but due to the data type being used. To illustrate
this, imagine you have two integers, 5 and 2. If you add them together, you expect 7 (and this is
what Java will return as well). However, if you divide 5 by 2, you already know the answer is 2.5.
However, Java is using integers, so the result of integer operations must be an integer. Therefore,
Java evaluates 5/2 = 2. The remainder is not included in the result.
This is where the modulo operator comes in. It will calculate the remainder in division. So, while
5/2 = 2 (and the remainder of 1 was ignored), 5%2 = 1 (here is that remainder of 1). Between the
two operators, you have the complete solution. It's interesting to note that the modulo operator
is often used to check whether a number is even or odd. For an even number, %2 will result in 0,
whereas for an odd number, %2 will result in 1.
In Java, expressions are evaluated following the usual mathematical order of operations. This means
in terms of precedence, the operators ( * ), ( / ), and ( % ) are processed before the operators ( + ) and ( - ).
For example, the expression 4+6*2 will be evaluated to 16. To change the order of processing, you
can use parentheses to indicate which operations should be evaluated first. The expression (4+6)*2
will consequently be evaluated to 20. When you use more than one operator with the same level of
precedence, the expression will be evaluated from left to right. The expression 6+2+4+5*6 will thus
be equivalent to (((6+2) +4)+(5*6)), or 42.
assignment Operators
The assignment operator assigns values to a variable. In previous examples, you read about the ( = )
operator, which assigns a value to a variable. Table 2-9 lists some important assignment operators.
 
Search WWH ::




Custom Search