In java, there are many things that are easy to ignore. Today, I saw a java puzzle on the Internet. The Code is as follows:
[Java]
BigInteger five = new BigInteger ("5 ");
BigInteger four = new BigInteger ("4 ");
BigInteger total = BigInteger. ZERO;
Total. add (five );
Total. add (four );
System. out. println (total );
At first glance, I think this code should output 9. After all, 4 + 5 = 9. In fact, if you run this code (this Code cannot be directly run, you need to modify it), you will be surprised to find that this code is printed out of 0.
Analysis:
Unchangeable types: String, BigDecimal, BigInteger, and various wrapper types are immutable types.
The variable String feature is described in another blog.
For example, the add method of BigInteger does not change the two operands, that is, the existing instance, but returns a new instance.
Conclusion:
When you call a method of an immutable object, if you change the method of the object, the existing instance does not change, but returns a new instance.