In what way are these statements different?
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.
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); }};
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With