Java Reference
In-Depth Information
If we insert this code into the
main
method of the
StartApplet1.java
or
StartApp1.java
programs described in Chapter 1, the output looks as follows:
Divide By Zero
=
x/y
=
Infinity
Divide negative value by zero
=
x/y
=
-Infinity
Positive underflow
=
0.0
Negative underflow
=
-0.0
Divide 1 by negative zero = -Infinity
Divide zero by zero = NaN
On some platforms, the symbols on the console for Infinity and Not-a-Number
differ from these.
2.13 Basic math in Java
The core Java language comes with some basic mathematical tools built into
it. In this section we look at simple arithmetic operations and the mathematical
functions provided by the
Math
class.
2.13.1 Arithmetic operations
The Java core language includes the simple arithmetic operators:
+
addition
-
subtraction
*
multiplication
/
division
%
modulo (remainder)
The addition operator
“
a+b
„
both adds numerical type values and also
performs string concatenation as discussed in Section 2.6. This is the only case
in Java of operator overloading. The subtraction operator
“
a-b
„
subtracts
b
from
a
,but the minus sign 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 truncated.
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 exception is thrown (error and exception handling
are discussed in Chapter 3).
If either
a
or
b
is a floating-point type and
b
is zero, the result is
+infinity
if
a
is a non-zero positive value
-infinity
if
a
is a non-zero negative value
NaN
if
a
is also zero.
Search WWH ::
Custom Search