Let's take a look at one of the following examples:
Copy Code code as follows:
Import Java.math.BigInteger;
public class Bigproblem {
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);
}
}
You might think that this program will print out 555000. After all, it sets the total to 0 in BigInteger, and then adds 5,000, 50,000, and 500,000 to the variable. If you run the program, you will find that it prints not 555000, but 0. Obviously, all these additions have no effect on total.
There is a good reason to explain this: the BigInteger instance is immutable. String, BigDecimal, and wrapper types: The same is true for integers, Long, short, Byte, Character, Boolean, float, and double, and you cannot modify their values. We cannot modify the values of existing instances, and these types of operations will return a new instance. At first, immutable types may seem unnatural, but they have many advantages over their corresponding variable types. Immutable types are easier to design, implement, and use; they are less likely to make mistakes and are more secure [EJ Item 13].
In order to perform a calculation on a variable that contains a reference to an immutable object, we need to assign the calculated result to the variable. This will produce the following program, which will print out the 555000 we expect:
Copy Code code as follows:
Import Java.math.BigInteger;
public class Bigproblem {
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 = Total.add (Fivethousand);
Total = Total.add (Fiftythousand);
Total = Total.add (Fivehundredthousand);
SYSTEM.OUT.PRINTLN (total);
}
}