I play around with java.math.BigInteger. Here is my java class,
public class BigIntegerTest{
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);
}
}
I think the result is 555000. But the actual is 0. Why ?
BigIntegerobjects are immutable. Their values cannot be changed, once created.When you call
.adda new BigInteger object is created and returned, and must be stored if you want to access its value.(It’s fine to say
total = total.add(...)because it’s just removing the reference to the oldtotalobject and reassigning it the reference to the new one created by.add).