Alberto Zaccagni
Alberto Zaccagni

Reputation: 31560

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;

Upvotes: 39

Views: 123522

Answers (3)

Jesper
Jesper

Reputation: 206796

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.

Upvotes: 21

Jon Skeet
Jon Skeet

Reputation: 1500385

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

Upvotes: 29

Sean Owen
Sean Owen

Reputation: 66886

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.

Upvotes: 3

Related Questions