Java Autoboxing and Unboxing Example

Java 5 introduced autoboxing and unboxing feature that is a convenient way to auto transform primitive data type to it’s corresponding java wrapper classes and vice versa.

Autoboxing in Java

Converting a primitive data type into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer or converting long to Long object.

Java compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class. For example a method with Integer argument can be called by passing int, java compiler will do the conversion of int to Integer.
  • Assigned to a variable of the corresponding wrapper class. For example, assigning a Long object to long variable.

Unboxing in Java

onverting an object of a wrapper type to its corresponding primitive data type is called unboxing.

Java compiler applies unboxing when an object of a wrapper class 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.

Here is a small java program showing examples of autoboxing and unboxing in java.

package com.journaldev.misc;

import java.util.ArrayList;
import java.util.List;

public class AutoboxingUnboxing {

    public static void main(String[] args) {
        int i = 5;
        long j = 105L;
        //passed the int, will get converted to Integer object at Runtime
        List<Long> list = new ArrayList<>();
        //autoboxing to add primitive type in collection classes

    private static void doSomething(Integer in){
        //unboxing, at runtime Integer.intValue() is called implicitly to return int
        int j = in;
        //unboxing, Integer is passed where int was expected

    private static void doPrimitive(int i) {

About Pankaj

If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my articles directly.

Recently I started creating video tutorials too, so do check out my videos on Youtube.

Some of the video tutorials on Udemy I would recommend are;

Join our email newsletter to get promo codes for almost 90% discount on these courses, and yes you will get a lot of free eBooks too, absolutely Free.

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to JournalDev Newsletter
Get the FREE access to JournalDev Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.