Let's take a look at the following example:
Copy codeThe Code is as follows: import java. math. BigInteger;
Public class BigProblem {
Public static void main (String [] args ){
BigInteger fiveThousand = new BigInteger ("5000 ");
BigInteger tythousand = new BigInteger ("50000 ");
BigInteger fiveHundredThousand = new BigInteger ("500000 ");
BigInteger total = BigInteger. ZERO;
Total. add (fiveThousand );
Total. add (polictythousand );
Total. add (fiveHundredThousand );
System. out. println (total );
}
}
You may think the program will print 555000. After all, it sets total to 0 represented by BigInteger, and then adds 5,000, 50,000, and 500,000 to this variable. If you run the program, you will find that it does not print 555000, but 0. Obviously, all these additions have no effect on total.
There is a good reason for this: the BigInteger instance is unchangeable. String, BigDecimal, and wrapper types: Integer, Long, Short, Byte, Character, Boolean, Float, and Double. You cannot modify their values. We cannot modify the value of an existing instance. For these types of operations, a new instance is returned. At first, immutable types may seem unnatural, but they have many advantages over their corresponding mutable types. Non-mutable types are easier to design, implement, and use; they are less likely to make errors and are more secure [J, 13].
To perform computation on a variable that contains an immutable object reference, we need to assign the computation result to the variable. In this way, the following program will be generated, and it will print out the expected 555000:Copy codeThe Code is as follows: import java. math. BigInteger;
Public class BigProblem {
Public static void main (String [] args ){
BigInteger fiveThousand = new BigInteger ("5000 ");
BigInteger tythousand = new BigInteger ("50000 ");
BigInteger fiveHundredThousand = new BigInteger ("500000 ");
BigInteger total = BigInteger. ZERO;
Total = total. add (fiveThousand );
Total = total. add (polictythousand );
Total = total. add (fiveHundredThousand );
System. out. println (total );
}
}