Note well: The same question applies for other immutable types, like String and Boolean.
I have a method like this (this is a simple example of a more complicated method):
Example 1
public BigDecimal addTwo(BigDecimal bigDecimal) {
bigDecimal = bigDecimal.add(new BigDecimal(2));
return bigDecimal;
}
I know, I could simply return bigDecimal.add(new BigDecimal(2))
. But it's only an example.
The problem with this code is that I can't add final
to the method parameter and Eclipse bothers me. So I would write:
Example 2
public BigDecimal addTwo(final BigDecimal bigDecimal) {
BigDecimal bigDecimalLocal = bigDecimal;
bigDecimalLocal = bigDecimalLocal.add(new BigDecimal(2));
return bigDecimalLocal;
}
I know, I can do directly BigDecimal bigDecimalLocal = bigDecimal.add(new BigDecimal(2))
. But I repeat, this is only an example.
The question is: when I do:
BigDecimal bigDecimalLocal = bigDecimal;
I'm not creating a new BigDecimal
. I'm assigning the same object to a different variable. I found on SO that a simple way to clone BigDecimal
is:
Example 3
BigDecimal bigDecimalLocal = new BigDecimal(bigDecimal.toString());
The question is: since BigDecimal
is immutable, is this really necessary? Can't I simple do as in example #2? I think the final
keyword could not be invalidated in that way.