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