Java Reference
In-Depth Information
< Day Day Up >
Puzzle 56: Big Problem
As a warm-up, test your knowledge of
BigInteger
. What does this program print?
import java.math.BigInteger;
public class BigProblem {
public static void main(String[] args) {
BigInteger fiveThousand = new BigInteger("5000");
BigInteger fiftyThousand = new BigInteger("50000");
BigInteger fiveHundredThousand
= new BigInteger("500000");
BigInteger total = BigInteger.ZERO;
total.add(fiveThousand);
total.add(fiftyThousand);
total.add(fiveHundredThousand);
System.out.println(total);
}
}
Solution 56: Big Problem
You might think that this program prints
555000
. After all, it sets
total
to the
BigInteger
representation for 0 and then adds 5,000, 50,000, and 500,000. If you ran the program, you found
that it doesn't print
555000
but
0
. Apparently all that addition has no effect on
total
.
There is a good reason for this:
BigInteger
instances are immutable.
So are instances of
String
,
BigDecimal
, and the wrapper types:
Integer
,
Long
,
Short
,
Byte
,
Character
,
Boolean
,
Float
, and
Double
. You can't change their values. Instead of modifying existing instances, operations on these
types return new instances. At first, immutable types might seem unnatural, but they have many
advantages over their mutable counterparts. Immutable types are easier to design, implement, and
Search WWH ::
Custom Search