Boxing and Unboxing

Figure 514. Stack of integer values Slide presentation Create comment in forum
final Stack<Integer> values = new Stack<>();

values.push(3);
values.push(1);
values.push(10);

while (!values.empty()) {
  final int i = values.pop();
  System.out.println(i);
}
10
1
3

Figure 515. Java collection features Slide presentation Create comment in forum

Figure 516. Behind the scenes Slide presentation Create comment in forum
final Stack<Integer> values =
  new Stack<>();

values.push(3);
values.push(1);
values.push(10);

while (!values.empty()) {
  System.out.println(values.pop().
     getClass().getTypeName());
}
java.lang.Integer
java.lang.Integer
java.lang.Integer

Figure 517. Boxing and unboxing Slide presentation Create comment in forum
int iPrimitive  = 7;

Integer iInteger = 
  iPrimitive;

int iPrimitiveFromInteger = 
  iInteger;
int iPrimitive  = 7;

Integer iInteger = 
  Integer.valueOf(iPrimitive);

int iPrimitiveFromInteger = 
  iInteger.intValue();
Boxing and unboxing Conventional Java

Defining a primitive int value.

Creating an instance of Integer by means of boxing.

Assigning an Integer's value to a primitive int by means of unboxing.

Defining a primitive int value.

Creating a new instance of Integer using the class method Integer valueOf​(int i).

Assigning an Integer's value to a primitive int using the int intValue() instance method.


Figure 518. Boxing syntax comparison Slide presentation Create comment in forum
final Stack<Integer> values
 = new Stack<>();

values.push(Integer.valueOf(3));
values.push(Integer.valueOf(1));
values.push(Integer.valueOf(10));

while (!values.empty()) {
  System.out.println(values.pop().
     intValue());
}
final Stack<Integer> values =
  new Stack<>();

values.push(3);
values.push(1);
values.push(10);

while (!values.empty()) {
  System.out.println(values.pop());
}

exercise No. 162

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