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
  • 980
  • 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
  • 155,977
  • 14
  • 207
  • 269
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,515
  • 2
  • 26
  • 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,180
  • 7
  • 31
  • 44
2

Try this:

BigDecimal bd1 = new BigDecimal(10);
BigDecimal bd2 = new BigDecimal(10);
bd1 = bd1.add(bd2);
System.out.println(bd1); /*Prints 20*/
1218985
  • 6,880
  • 2
  • 22
  • 27
1

You need to store the result in a new variable:

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