Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a Double object with a primitive double value

What is happening when a java.lang.Double object is initialized without using a call to the constructor but instead using a primitive? It appears to work but I'm not quite sure why. Is there some kind of implicit conversion going on with the compiler? This is using Java 5.

public class Foo {

    public static void main(String[] args) {
        Double d = 5.1;

        System.out.println(d.toString());

    }

}
like image 370
Doug Porter Avatar asked Jul 20 '10 13:07

Doug Porter


1 Answers

This is called Autoboxing which is a feature that was added in Java 5. It will automatically convert between primitive types and the wrapper types such as double (the primitive) and java.lang.Double (the object wrapper). The java compiler automatically transforms the line:

Double d = 5.1;

into:

Double d = Double.valueOf(5.1);
like image 143
krock Avatar answered Nov 16 '22 02:11

krock