I was wondering if these two are the same. Can anyone verify? (I am trying to replace the 1st with the 2nd)
BigDecimal totalCurrentSales = new BigDecimal(0);
and
BigDecimal totalCurrentSales = BigDecimal.ZERO;
The reason I ask is that it is improper to declare it the first way since you are not supposed to create instances of already existing BigInteger
and BigDecimal (ZERO, ONE, TEN)
. So I was wondering if I could say it the second way and it still be considered creating an instance. Instead of me having to create a variable zero
or something that is equal to BigDecimal.ZERO
. Or are there any other ways?
I tried
BigDecimal totalCurrentSales = new BigDecimal(BigDecimal.ZERO);
but eclipse wasn't too happy.
Mathematically, they're the same. Plus, since BigDecimals are immutable, you don't need to worry about creating new instances to do new calculations. As soon as you perform some operation on your totalCurrentSales
instance, you'll actually be creating a new BigDecimal and reassigning the totalCurrentSales
reference to the new value.
From a instantiation perspective, they're not necessarily exactly the same. In the OpenJDK 6b14 implementation, for example, BigDecimal.ZERO
is created by invoking the private new BigDecimal(BigInteger, long, int)
constructor with values BigInteger.ZERO
, 0
, and 0
.
From a code quality perspective, using BigDecimal.ZERO
is preferable to new BigDecimal(0)
as you avoid the extra instantiation and having a literal in your code.