The Java core language includes five simple arithmetic operators:
+,-,*,/,% (where
% is the modulo operator).
In binary operations, if either the first or second operand
is a floating point type and the other is an integer type, the integer
operand will convert to floating point. If it involves two two different
integer types, the result will be in the wider type.
The addition operator '+'
adds numeric values and also performs string concatenation, as in
String
str = "ab"+"cde"
results in str
reference the string"abcde".
This is the only case of an overloaded operator in Java.
The dash '-'
acts as the subtraction operator in "a
- b" and subtracts b from a. However, it can also act
as the unary minus operator that performs negation on a single
number ( a = -b)
.
The "a/b"
division operator divides a
by b according
to these rules:
- if both a
and b
are integers the result is an integer with the remainder dropped
- if either a
or b is
a floating point type, the result is floating point.
- if a
and b
are integers and b
is zero, an ArthmeticException
error is thrown.
- If either a
or b is
a floating point type and b
is zero, the result is
- positive
infinity if a
is a non-zero positive value
- negative
infinity if a
is a non-zero negative value
- NaN
if a
is also zero.
See the Floating Point sections for
details on how these anomalous values are actually represented.
The "a%b"
modulo operator returns the remainder of a
divided by b.
For example,
5%3
returns a value of 2. If either operand is floating point, the
result will be the floating point remainder.
Note: The Math class method
Math.IEEEremainder(double
a,double b)
will also compute a remainder of a/b
for two double type values according to the specific rules of the
IEEE 754 standard. (See the Math
class specifications.)
Note: There is no exponent
operator such as a**b
for a to
the b power.
Instead, you must use the Math
class method Math.pow(double
a,double b)that computes a
to the b
power and returns the result as a double
type.
Latest update: Dec.12.2003
|