erp
erp

Reputation: 3014

BigDecimal.ZERO vs. new BigDecimal(0). Which to use and why?

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.

Upvotes: 41

Views: 103235

Answers (2)

Nathan Hughes
Nathan Hughes

Reputation: 96434

BigDecimal doesn't have a constructor that takes a BigDecimal as an argument, so that explains why Eclipse would not be happy with that.

BigDecimal is immutable, which means once you create an object its state never changes.

Also BigDecimal's equals and hashcode methods are overridden to go by value, as opposed to Object's default implementation, which compares references. So there is no difference between BigDecimal.ZERO and new BigDecimal("0") from the point of view of how they are used, except that creating a new instance is more work for the JVM (and will generate more garbage when you don't need that object any more).

BigDecimal's being immutable and value-based means what specific reference is used won't matter to the code using the BigDecimal.

Because BigDecimal.ZERO is already created for you and comparisions between BigDecimals are by value, it makes sense to minimize the number of values you use so that your programs create less garbage. That's why you're getting encouraged to use BigDecimal.ZERO.

Upvotes: 13

bdkosher
bdkosher

Reputation: 5883

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.

Upvotes: 60

Related Questions