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 ?
BigInteger
objects are immutable. Their values cannot be changed, once created.
When you call .add
a new BigInteger object is created and returned, and must be stored if you want to access its value.
BigInteger total = BigInteger.ZERO;
total = total.add(fiveThousand);
total = total.add(fiftyThousand);
total = total.add(fiveHundredThousand);
System.out.println(total);
(It's fine to say total = total.add(...)
because it's just removing the reference to the old total
object and reassigning it the reference to the new one created by .add
).
Try this
BigInteger fiveThousand = new BigInteger("5000");
BigInteger fiftyThousand = new BigInteger("50000");
BigInteger fiveHundredThousand = new BigInteger("500000");
BigInteger total = BigInteger.ZERO;
total = total.add(fiveThousand).add(fiftyThousand).add(fiveHundredThousand);
System.out.println(total);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With