Java double initialization

Alberto Zaccagni picture Alberto Zaccagni · Sep 18, 2009 · Viewed 88k times · Source

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;

Answer

Jon Skeet picture Jon Skeet · Sep 18, 2009

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...