A memo because my colleague was addicted to treating Big Decimal.
~~ Variable value ~~ When manipulating an object, rewriting the value of the ~~ variable ~~ object itself is called "mutable", and not rewriting it is called "immutable". In Java, ~~ int and double ~~ Calendar are mutable, and String is immutable.
BigDecimal API documentation https://docs.oracle.com/javase/jp/8/docs/api/java/math/BigDecimal.html
Let's take a look at the add method that adds.
/**
value(this+augend)Scale is max(this.scale(), augend.scale())Returns the Big Decimal that is.
Parameters: augend -The value to add to this Big Decimal.
Return value: this + augend
*/
public BigDecimal add(BigDecimal augend)
Now, what is the output of the following code?
public static void main(String args[]) {
BigDecimal a = new BigDecimal("1");
BigDecimal b = new BigDecimal("2");
a.add(b);
System.out.println(a);
}
Output result.
1
that? Isn't it 3? I thought you. You've overlooked an important sentence in the API documentation.
** Immutable **, arbitrary precision signed decimal number.
In other words, this code meant to ** create a new BigDecimal object with a value of a + b ** and return that object. The value of a itself does not change at all.
a.add(b);
It was a code that calculates money by extracting a numerical value from DB with Big Decimal, but I proceeded with processing without assigning the result of a method such as add to a variable, and it was a bug.
You can't see immutable things just by writing the code ... It was a nasty bug.