Dig into Java immutable types

  • 2020-04-01 01:59:52
  • OfStack

Let's start with the following example:

    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 would print out 555,000. After all, it sets total to 0 in BigInteger, and then adds 5,000, 50,000, and 500,000 to this variable. If you run the program, you will see that instead of 555,000, it prints 0. Obviously, all these additions have no effect on total.

There is a good reason for this: the BigInteger instance is immutable. The same is true for String, BigDecimal, and wrapper types: Integer, Long, Short, Byte, Character, Boolean, Float, and Double; you cannot change their values. We cannot modify the values of existing instances, and operations on these types return new instances. At first, immutable types may seem unnatural, but they have many advantages over their mutable counterparts. Immutable types are easier to design, implement, and use; They are less likely to go wrong and are safer [EJ Item 13].

To perform a calculation on a variable that contains a reference to an immutable object, we need to assign the result of the calculation to that variable. Doing so produces the following program, which prints out the 555,000 we expect:

    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);  
        }  
    }  


Related articles: