Boxing and unboxing

Figure 557. Stack of integer values Slide presentation
final Stack<Integer> values = new Stack<>();

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

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

Figure 558. Java™ collection features Slide presentation

Figure 559. Behind the scenes Slide presentation
final Stack<Integer> values =
  new Stack<>();

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

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

Figure 560. Boxing and unboxing Slide presentation
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 561. Boxing syntax comparison Slide presentation
final Stack<Integer> values
 = new Stack<>();

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

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

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

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

exercise No. 195

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.