Java Reference
In-Depth Information
There is no limit to the precision of a
BigDecimal
object. The
divide
method may throw
an
ArithmeticException
if the result cannot be terminated. However, you can use
the overloaded
divide(BigDecimal d, int scale, int roundingMode)
method to
specify a scale and a rounding mode to avoid this exception, where
scale
is the maxi-
mum number of digits after the decimal point. For example, the following code creates two
BigDecimal
objects and performs division with scale
20
and rounding mode
BigDecimal.ROUND_UP
.
BigDecimal a =
new
BigDecimal(
1.0
);
BigDecimal b =
new
BigDecimal(
3
);
BigDecimal c = a.divide(b,
20
, BigDecimal.ROUND_UP);
System.out.println(c);
The output is
0.33333333333333333334
.
Note that the factorial of an integer can be very large. Listing 10.11 gives a method that can
return the factorial of any integer.
L
ISTING
10.11
LargeFactorial.java
1
import
java.math.*;
2
3
public class
LargeFactorial {
4
public static void
main(String[] args) {
5 System.out.println(
"50! is \n"
+ factorial(
50
));
6 }
7
8
public static
BigInteger factorial(
long
n) {
9
10
BigInteger result = BigInteger.ONE;
constant
for
(
int
i =
1
; i <= n; i++)
11
12
13
result = result.multiply(
new
BigInteger(i +
""
));
multiply
return
result;
14 }
15 }
50! is
30414093201713378043612608166064768844377641568960512000000000000
BigInteger.ONE
(line 9) is a constant defined in the
BigInteger
class.
BigInteger.ONE
is
the same as
new BigInteger("1")
.
A new result is obtained by invoking the
multiply
method (line 11).
10.21
What is the output of the following code?
✓
✓
Check
Point
public class
Test {
public static void
main(String[] args) {
java.math.BigInteger x =
new
java.math.BigInteger(
"3"
);
java.math.BigInteger y =
new
java.math.BigInteger(
"7"
);
x.add(y);
System.out.println(x);
}
}