Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 509
Alberto Zaccagni Avatar asked Sep 18 '09 08:09

Alberto Zaccagni


People also ask

What is double initialization?

Double brace initialization is a technique to create and initialize an object within a single expression. Generally, when we create an object of any Collection (ArrayList, HashMap, HashSet etc.) we consume 2-3 lines on declaration and initialization.

What is double brace initialization in Java?

Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g. new ArrayList<Integer>() {{ add(1); add(2); }};


2 Answers

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

like image 118
Jon Skeet Avatar answered Sep 29 '22 16:09

Jon Skeet


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.

like image 37
Jesper Avatar answered Sep 29 '22 16:09

Jesper