Java Reference
In-Depth Information
}
}
Handling Very Large Numbers
Problem
You need to handle integer numbers larger than
Long.MAX_VALUE
or floating-point values
larger than
Double.MAX_VALUE
.
Solution
Use the
BigInteger
or
BigDecimal
values in package
java.math
, as shown in
Example 5-7. BigNums.java
System
.
out
.
println
(
"Here's Long.MAX_VALUE: "
+
Long
.
MAX_VALUE
);
BigInteger bInt
=
new
new
BigInteger
(
"3419229223372036854775807"
);
System
.
out
.
println
(
"Here's a bigger number: "
+
bInt
);
System
.
out
.
println
(
"Here it is as a double: "
+
bInt
.
doubleValue
());
Note that the constructor takes the number as a string. Obviously you couldn't just type the
numeric digits because, by definition, these classes are designed to represent numbers larger
than will fit in a Java
long
.
Discussion
Both
BigInteger
and
BigDecimal
objects are immutable; that is, once constructed, they al-
ways represent a given number. That said, a number of methods return new objects that are
mutations of the original, such as
negate()
, which returns the negative of the given
BigIn-
teger
or
BigDecimal
. There are also methods corresponding to most of the Java language
built-in operators defined on the base types
int
/
long
and
float
/
double
. The division meth-
od makes you specify the rounding method; consult a book on numerical analysis for details.
Example 5-8. BigNumCalc
public
public class
class
BigNumCalc
BigNumCalc
{