Java Reference
In-Depth Information
Arithmetic Operators
Arithmetic operators manipulate two or more numeric values. Table 3-7
lists seven arithmetic operations, the operator symbols, an example, and example
results.
Table 3-7
Arithmetic Operators in Java
OPERATOR
OPERATION
SYMBOL
EXAMPLE
RESULT
Cast
(data type) literal
(int) 20.3
20 (conversion to integer
or variable
results in loss of precision)
Multiplication
*
20 * 3
60
Division
/
20.0/3.0
6.6666667 for float
6.666666666666667 for
double
Integer Division
/
20 / 3
6 (the remainder is
dropped because the
operands both are
integers)
Modular Division
%
20 % 3
2 (only the integer
remainder is stored)
Addition
+
20 + 3
23
Subtraction
-
20 - 3
17
Table 3-7 lists the arithmetic operators in the order of operator precedence.
Order of operator precedence is a predetermined order that defines the
sequence in which operators are evaluated and resolved when several operations
occur in an expression. You may be familiar with most of the arithmetic opera-
tors, as operator symbols in Java are similar to regular algebraic symbols. Com-
monly used arithmetic operators are the plus sign (+), used to add or sum two
numbers, and the asterisk (*), used to multiply two numbers.
The less familiar operations, with respect to Java, are integer and modular
division. Integer division is performed when both the dividend and the divisor
are integers. When performing integer division, Java forces the result to be an
integer because it is a primitive data type; it then drops any remainder. Modular
division , or remainder division, is used to store any truncated remainder value
from integer division. The modulus operator (%), which also is called the
remainder operator, is entered between two integers and performs modular
division. Modular division is common to many programming languages.
The type of division used in a program can return different results. For
example, if you wanted to convert 168 minutes to hours and minutes, regular
division using double data types would result in 2.8 hours:
decimalAnswer = 168D / 60D;
decimalAnswer = 2.8;
 
Search WWH ::




Custom Search