Java Reference
In-Depth Information
S
ELF
C
HECK
1.
Which are the most commonly used number types in Java?
2.
When does the cast
(long) x
yield a different result from the call
Math.round(x)
?
3.
How do you round the
double
value
x
to the nearest
int
value,
assuming that you know that it is less than 2 10
9
?
136
137
A
DVANCED
T
OPIC
4.1: Big Numbers
If you want to compute with really large numbers, you can use big number objects.
Big number objects are objects of the
BigInteger
and
BigDecimal
classes in
the
java.math
package. Unlike the number types such as
int
or
double
, big
number objects have essentially no limits on their size and precision. However,
computations with big number objects are much slower than those that involve
number types. Perhaps more importantly, you can't use the familiar arithmetic
operators such as (+-*) with them. Instead, you have to use methods called
add, subtract
, and
multiply
. Here is an example of how to create two big
integers and how to multiply them.
BigInteger a = new BigInteger("1234567890");
BigInteger b = new BigInteger("9876543210");
BigInteger c = a.multiply(b);
System.out.println(c); //
Prints 12193263111263526900
The
BigDecimal
type carries out floating-point computation without roundoff
errors. For example,
BigDecimal d = new BigDecimal("4.35");
BigDecimal e = new BigDecimal ("100");
BigDecimal f = d.multiply(e);
System.out.println(f); //
Prints 435.00