Initializing a Double object with a primitive double value
Asked Answered
R

3

10

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());

    }

}
Redeploy answered 20/7, 2010 at 13:57 Comment(2)
Now knowing that it's called autoboxing you can find a lot of interesting articles in SO :)Locally
Autboxing, that's what I was looking for. Thanks SO!Redeploy
E
11

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);
Eliaseliason answered 20/7, 2010 at 13:58 Comment(0)
B
5

It is called AutoBoxing

Autoboxing and Auto-Unboxing of Primitive Types Converting between primitive types, like int, boolean, and their equivalent Object-based counterparts like Integer and Boolean, can require unnecessary amounts of extra coding, especially if the conversion is only needed for a method call to the Collections API, for example.

The autoboxing and auto-unboxing of Java primitives produces code that is more concise and easier to follow. In the next example an int is being stored and then retrieved from an ArrayList. The 5.0 version leaves the conversion required to transition to an Integer and back to the compiler.

Before

ArrayList<Integer> list = new ArrayList<Integer>();
  list.add(0, new Integer(42)); 
  int total = (list.get(0)).intValue();

After

ArrayList<Integer> list = new ArrayList<Integer>();
  list.add(0, 42);
  int total = list.get(0);
Beaverette answered 20/7, 2010 at 13:59 Comment(0)
A
3

It's called autoboxing.

Appetizer answered 20/7, 2010 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.