Java: Beware of Immutable Objects
By admin on Aug 24, 2008 in Java, Programming
Have a look at the following code
1: BigInteger value1 = new BigInteger("1000");
2: BigInteger value2 = BigInteger.ZERO;
3:
4: value2.add(value1);
5: System.out.println(value2.toString());
The result is “0” since for as BigInteger instance is immutable.
To get the correct result, you should do the following
1: BigInteger value1 = new BigInteger("1000");
2: BigInteger value2 = BigInteger.ZERO;
3:
4: BigInteger result = value2.add(value1);
5: System.out.println(result.toString());
You should get the result in another variable.
This apply to other immutable objects like BigDecimal, String, Long, Integer, etc..
Sorry, comments for this entry are closed at this time.