Java Reference
In-Depth Information
The Multiplicative Operators
The operators
*
,
/
, and
%
are referred to as the
multiplicative operators
. They have a higher
precedence of operation than additive operators. The multiplicative operators can only be
performed on the numeric primitive types; otherwise, a compiler error occurs.
As with + and
-
, the multiplicative operators promote both operands to the data type of
the larger operand. If both operands are smaller than an
int
, both operands are converted
to
int
s before the multiplication occurs. For example, what is the result of the following
statements?
4. int a = 26, b = 5;
5. double d = a / b;
The expression
a / b
is integer division, which results in the
int
5. Therefore, the value
of
d
is 5.0. The fact that we store the result in a
double
does not affect the arithmetic
because the assignment takes place after the arithmetic is already performed.
If one of the operands is a
float
or
double
, the expression is evaluated using fl oating-
point arithmetic and the result will be a
float
or
double
depending on the operand types.
For example, what is the result of the following statements?
8. int a = 26;
9. float f = a / 5.0F;
Because 5.0 is a
float
(by virtue of the
âFâ
appended to it), the
int
a
is promoted to
a
float
and fl oating-point division is performed. The value of
f
is 5.2 after this code
executes.
The MODULUS Operator
The modulus operator, also known as the remainder operator, evaluates the remainder
of two numbers when they are divided. For example, what is the result of the following
expression?
int x = 12 % 5;
The remainder of 12 divided by 5 is 2, so
x
is 2.
If the fi rst operand is negative, so is the result of the modulus. The value of
y
after the
following statement is -1:
int y = -17 % 4;
In Java you can evaluate the remainder of fl oating-point numbers as well. While not
as intuitive as integer modulus, there is still a remainder in fl oating-point division. For
example, what is the output of the following code?
System.out.println(12.4 % 3.2);
Search WWH ::
Custom Search