Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between BigDecimal("0") and BigDecimal.ZERO?

Either for comparisons or initialization of a new variable, does it make a difference which one of these you use?

I know that BigDecimal.ZERO is a 1.5 feature, so that's a concern, but assuming I'm using 1.5 does it matter?

Thanks.

like image 525
MattGrommes Avatar asked Nov 06 '08 18:11

MattGrommes


People also ask

How do I know if BigDecimal is 0?

Using the compareTo Method Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. Therefore, we can check BigDecimal. ZERO. compareTo(givenBdNumber) == 0 to decide if givenBdNumber has the value zero.

How can you tell if BigDecimal value is greater than zero?

using ". intValue()" on BigDecimal object is not right when you want to check if its grater than zero. The only option left is ". compareTo()" method.

What is the default value of BigDecimal?

If you are using type BigDecimal, then its default value is null (it is object, not primitive type), so you get [1] automatically.


2 Answers

BigDecimal.ZERO is a predefined constant and therefore doesn't have to be evaluated from a string at runtime as BigDecimal("0") would be. It will be faster and won't require creation of a new object.

If your code needs to run on pre-1.5, then you can use the (much maligned) Singleton pattern to create an object equivalent to BigDecimal.ZERO. The first time it is used, it would call BigDecimal("0") to create a zero object, and return that object on subsequent calls. Otherwise, if your code is running on a 1.5 system, your singleton object can just return BigDecimal.ZERO with no runtime penalty.

like image 184
Greg Hewgill Avatar answered Sep 21 '22 11:09

Greg Hewgill


Using ZERO doesn't create a new object or require any parsing. Definitely the way to go.

like image 29
Jon Skeet Avatar answered Sep 22 '22 11:09

Jon Skeet