-1

When I want to add two BigDecimal objects together

public void addBalanceWallet(BigDecimal balanceWallet) {
        this.balanceWallet.add(balanceWallet);
}

There is no effect. Additionally, the IDE shows enter image description here

Why can't I add these two objects together?

JONKI
  • 535
  • 5
  • 10
  • 24
  • 4
    BigDecimal objects are immutable. The result of the addition is returned. You could for example compute `this.balanceWallet = this.balanceWallet.add(balanceWallet);` – President James K. Polk Sep 30 '21 at 22:30
  • 1
    ... and when you add these two values together what would you like to do with the sum? – PM 77-1 Sep 30 '21 at 22:30
  • I am increasing the balance of the user's wallet. I used BigDecimal because it has high precision, but I can see that it is pointless. – JONKI Sep 30 '21 at 22:32
  • Incidentally if this is for Bitcoin you don't need `BigDecimal` at all, because the total outstanding satoshis will never exceed about 2e15, which is less than a Java (signed) `long` can handle by a factor of a thousand, and any single wallet will be even less. – dave_thompson_085 Sep 30 '21 at 22:40
  • “Immutable” is the very first word in the [Javadoc for `BigDecimal`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/math/BigDecimal.html). – Basil Bourque Oct 01 '21 at 00:17

2 Answers2

4

You are not assigning the return value (which is the actual result of the addition) to anything and thus the "Result (...) is ignored" message. I guess you want to do the following:

public void addBalanceWallet(BigDecimal balanceWallet) {
    this.balanceWallet = this.balanceWallet.add(balanceWallet);
}
João Dias
  • 16,277
  • 6
  • 33
  • 45
3

You have to save the return value. For example:

public BigDecimal addBalanceWallet(BigDecimal balanceWallet) {
        return this.balanceWallet.add(balanceWallet);
}

And afterwards:

BigDecimal addResult = this.balanceWallet.addBalanceWallet(some_big_decimal)
Ofir
  • 590
  • 9
  • 19