Boxing and Unboxing

Figure 444. 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 445. Java collection features Slide presentation Create comment in forum

Figure 446. 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 447. 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 448. 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());
}