## Boxing and Unboxing

No. 171

### Auto boxing int to Double?

Q:

Consider the following two code snippets:

 Double d = 3.0; Double d = 3; o.K. Compile time error:Incompatible types. Required: java.lang.Double Found: int

Explain this result. Hint: You may want to read chapter 5 and section 5.2 in particular from the The Java® Language Specification.

A:

3.0 is a double literal. For the sake of clarification we may rewrite the working code snippet:

double doubleValue = 3.0;
Double d = doubleValue;

With autoboxing on offer the compiler will silently box the value of type double into a corresponding instance of type Double.

On contrary 3 is an int literal allowing for re-writing the second snippet as:

int intValue = 3.0;
Double d = intValue;

The section does not define an int to Double boxing conversion: The compiler will thus not perform auto boxing from int do Double.

An int could however be auto-boxed into an Integer. But Double not being a subtype of Integer disallows a widening reference conversion.