Why BigDecimal.Zero exist in Java where as Double.zero doesn't

64 Views Asked by At

I am curious to understand why do we see BigDecimal.Zero but not Double.Zero, so if we need to assign a double variable as Zero then we need to cast it to (double) 0.

Any specific reasons creators added a special zero variable for bigdecimal.

1

There are 1 best solutions below

4
Sweeper On

so if we need to assign a double variable as Zero then we need to cast it to (double) 0.

No. This compiles:

double d = 0;

so does this:

double d = 0.0;

The first one works because assignment contexts allow a widening primitive conversion (from int to double).

If you're talking about the Double wrapper, this also compiles:

Double d = 0.0;

There is a zero value for double that you can easily write - in fact, more easily than BigDecimal.ZERO - it's just written 0.0. And because assignment contexts allow a boxing conversion, you can assign 0.0 to the wrapper Double too.

BigDecimal.ZERO is not the rule - it's the exception. The compiler knows about all the primitive numeric types, and their "zeroes" are baked into the language - 0, 0L, 0.0, 0.0f etc.

The compiler doesn't know about BigDecimal. BigDecimal is just a part of the JDK, the standard library, not a part of the Java language.

The language specifications does not say that there is a conversion from double to BigDecimal in an assignment context, so you can't do

BigDecimal d = 0.0;

And that's why there is BigDecimal.ZERO.