Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is java.math.BigInteger's usage wrong?

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 ?

like image 943
Sai Ye Yan Naing Aye Avatar asked Dec 04 '22 14:12

Sai Ye Yan Naing Aye


2 Answers

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).

like image 196
Alnitak Avatar answered Dec 16 '22 18:12

Alnitak


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);
like image 29
mssb Avatar answered Dec 16 '22 17:12

mssb