Java Reference
InDepth Information
int
a
=
2
;
int
v
=
++
a
+
++
a
*
++
a
;
Although the multiplication is performed before the addition, the operands of the
+
operator are evaluated first. As the operands of ++ are both a+, these are evaluated
to
3
and
4
, and so the expression evaluates to
3 + 4 * 5
, or
23
.
Arithmetic Operators
The arithmetic operators can be used with integers, floatingpoint numbers, and
even characters (i.e., they can be used with any primitive type other than
boolean
).
If either of the operands is a floatingpoint number, floatingpoint arithmetic is
used; otherwise, integer arithmetic is used. This matters because integer arithmetic
and floatingpoint arithmetic differ in the way division is performed and in the way
underflows and overflows are handled, for example. The arithmetic operators are:
Addition (
+
)
The
+
operator adds two numbers. As we'll see shortly, the
+
operator can also
be used to concatenate strings. If either operand of
+
is a string, the other one is
converted to a string as well. Be sure to use parentheses when you want to com‐
bine addition with concatenation. For example:
System
.
out
.
println
(
"Total: "
+
3
+
4
);
// Prints "Total: 34", not 7!
Subtraction (

)
When the

operator is used as a binary operator, it subtracts its second
operand from its first. For example, 73 evaluates to 4. The

operator can also
perform unary negation.
Multiplication (
*
)
The
*
operator multiplies its two operands. For example, 7*3 evaluates to 21.
Division (
/
)
The
/
operator divides its first operand by its second. If both operands are inte‐
gers, the result is an integer, and any remainder is lost. If either operand is a
floatingpoint value, however, the result is a floatingpoint value. When divid‐
ing two integers, division by zero throws an
ArithmeticException
. For
floatingpoint calculations, however, division by zero simply yields an infinite
result or NaN:
7
/
3
// Evaluates to 2
7
/
3.0f
// Evaluates to 2.333333f
7
/
0
// Throws an ArithmeticException
7
/
0.0
// Evaluates to positive infinity
0.0
/
0.0
// Evaluates to NaN
Modulo (
%
)
The
%
operator computes the first operand modulo the second operand (i.e., it
returns the remainder when the first operand is divided by the second operand
an integral number of times). For example, 7%3 is 1. The sign of the result is