Is using java.math.BigInteger used?

I play 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 value is 0 . Why?

+4
source share
2 answers

BigInteger objects are immutable. Their values ​​cannot be changed after creation.

When you call .add , a new BigInteger object is created and returned, and must be saved 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 good to say total = total.add(...) , because it simply removes the link to the old total object and reassigns it to the new one created by .add ).

+14
source

try it

  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); 
+2
source

All Articles