Skip to content
Advertisement

Java double initialization

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;

Advertisement

Answer

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…

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement