RSS Feed for This PostCurrent Article

Java: Beware of Immutable Objects

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


Trackback URL


Sorry, comments for this entry are closed at this time.