views:

356

answers:

4

In what way are these statements different?

  1. double dummy = 0;
  2. double dummy = 0.0;
  3. double dummy = 0.0d;
  4. double dummy = 0.0D;
+1  A: 

The last 3 should be identical. The literal on the right side is a double already. The 'd' or 'D' is implicit when you have a decimal literal.

The first one is slightly different in that 0 is an int literal, which will be widened to a double. I don't know if that even produces different byte code in this case or not; the result should be identical anyway.

Sean Owen
Thank you for the reply, I know the results are identical, I want to know the differences under the hood.
Alberto Zaccagni
For "0.0", "0.0d" and "0.0D" there are really no differences under the hood. Those are three ways to write a double literal, they all are exactly equivalent.
Jesper
A: 

for Java I do not know exactly, in C this can be really dangerous if you omit this D at the end since it will not change upper bytes, which can have effect that in your variable lies number which you actually did not put in!

In Java I had a really big problem with instatntiating BigDecimal - new BigDecimal(0) and new bigDecimal(0L) is NOT the same thing, you can feel it if you migrate your code from Java 1.4 to Java 1.5. Don't know why they were sloppy about it, maybe they had to do it that way.

ante.sabo
+6  A: 

Having tried a simple program (using both 0 and 100, to show the difference between "special" constants and general ones) the Sun Java 6 compiler will output the same bytecode for both 1 and 2 (cases 3 and 4 are identical to 2 as far as the compiler is concerned).

So for example:

double x = 100;
double y = 100.0;

compiles to:

0:  ldc2_w #2; //double 100.0d
3:  dstore_1
4:  ldc2_w #2; //double 100.0d
7:  dstore_3

However, I can't see anything in the Java Language Specification guaranteeing this compile-time widening of constant expressions. There's compile-time narrowing for cases like:

byte b = 100;

as specified in section 5.2, but that's not quite the same thing.

Maybe someone with sharper eyes than me can find a guarantee there somewhere...

Jon Skeet
Could you suggest a good resource where one can read about what ldc2_w and the other instructions mean?
Alberto Zaccagni
The JVM specification: http://java.sun.com/docs/books/jvms/
Jon Skeet
Thanks
Alberto Zaccagni
+1  A: 

For the first one:

double dummy = 0;

the integer literal 0 is converted to a double with a widening primitive conversion, see 5.1.2 Widening Primitive Conversion in the Java Language Specification. Note that this is done entirely by the compiler, it doesn't have any impact on the produced bytecode.

For the other ones:

double dummy = 0.0;
double dummy = 0.0d;
double dummy = 0.0D;

These three are exactly the same - 0.0, 0.0d and 0.0D are just three different ways of writing a double literal. See 3.10.2 Floating-Point Literals in the JLS.

Jesper