4

I have 2 BigDecimal numbers. I am trying to add them. My code is as follow:

BigDecimal bd1 = new BigDecimal(10);
BigDecimal bd2 = new BigDecimal(10);

bd1.add(bd2);

Here I am expecting the value of bd1 20 but again and again it's showing 10. It's not being added. Please help if I have done something wrong.

zaz
  • 970
  • 1
  • 7
  • 8

5 Answers5

10

BigDecimal values are immutable, You need to assign the value to the result of add:

bd1 = bd1.add(bd2);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
3

BigDecimal is immutable. Every operation returns a new instance containing the result of the operation.

Reading Java Doc about BigDecimal helps you to understand better.

If you want to store sum of bd1 and bd2 in bd1 , you have to do

bd1 = bd1.add(bd2);
Community
  • 1
  • 1
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
3

Reimeus is right. You need to assign the value to the result like this:

bd1 = bd1.add(bd2);

If you want to know details about immutable you can refer to following link:

What is meant by immutable?

Community
  • 1
  • 1
ray
  • 4,210
  • 8
  • 35
  • 46
2

Try this:

BigDecimal bd1 = new BigDecimal(10);
BigDecimal bd2 = new BigDecimal(10);
bd1 = bd1.add(bd2);
System.out.println(bd1); /*Prints 20*/
1218985
  • 7,531
  • 2
  • 25
  • 31
1

You need to store the result in a new variable:

BigDecimal bd3 = bd1.add(bd2);
Stijn Haus
  • 481
  • 3
  • 18