Autoboxing and Unboxing

By Raul Rios

The autoboxing and unboxing Java features let you write cleaner and easier-to-read code by allowing you to use either primitive data types or their corresponding wrapper objects. Java then automatically makes the needed conversions in code at runtime.

Conversion

Applied when

Autoboxing

Primitive → Wrapper

A primitive value is:

Passed as a parameter to a method that expects an object of the corresponding wrapper class

Assigned to a variable of the corresponding wrapper class.

Unboxing

Wrapper → Primitive

A wrapper object is:

Passed as a parameter to a method that expects a value of the corresponding primitive type

Assigned to a variable of the corresponding primitive type

Used in expressions with operators

Autoboxing and unboxing both work for all primitive data types, including char and boolean.

1

2

3

4

5

6

7

8

9

10

11

12

13

// Example 1: Autoboxing by parameter passing

List<Integer>list=newArrayList<>();

inti=8;

list.add(i);// converted to: list.add(Integer.valueOf(i));

// Example 2: Unboxing by assignment

i=list.get(0);// converted to: i = list.get(0).intValue();

// Example 3: Unboxing by using operators

Integera=newInteger(1);

i=(a+2);// converted to: i = (a.intValue() + 2);

That’s all coders! If you have any comments or questions, you can drop me a line or leave a comment below and I will be pleased to help you.

In case you’re looking for a complete (but still short, precise and to-the-point) study guide to help you get your valuable Oracle® Java Programmer certification, including many tricky real-exam-like questions, study sheets, and other bonuses, then the Java Certification Roadmap book is your book.

Finally, if you found this content useful and know more programmers, colleagues or friends that may be interested in getting the Java Certification, click one of the buttons belowclick the button on the bottom left corner of your screen to let them know about the Java Certification Roadmap.