Autoboxing and unboxing in java

java dev.to

In Java, we usually work with two types of data primitive values like int, double and objects (Non-primitive). At some point, we may need to convert between these two. Java makes this easier with something called autoboxing and unboxing.

Primitive vs Object

Primitive types are simple and store values directly.

int a = 10;
Enter fullscreen mode Exit fullscreen mode

Here, a just holds the value 10.

Objects are a bit different. They don’t store the value directly, instead they refer to a location where the value is stored.

String name = "Java";
Enter fullscreen mode Exit fullscreen mode

Wrapper classes like Integer, Double are also objects. They are mainly used when we need primitives in object form.

Autoboxing

Autoboxing means converting a primitive value into its corresponding object automatically.

int a = 10;
Integer obj = a;
Enter fullscreen mode Exit fullscreen mode

We are not doing any conversion manually here, Java handles it in the background.

Unboxing

Unboxing is just the reverse of that. It converts an object back into a primitive value.

Integer obj = 20;
int b = obj;
Enter fullscreen mode Exit fullscreen mode

Again, no manual work needed.

Why do we even need this?

One common place where this is useful is collections.

For example, ArrayList cannot store primitive values. It only works with objects. So when we add an int, it gets converted automatically.

import java.util.*;

public class Example {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();

        list.add(50);
        int value = list.get(0);

        System.out.println(value);
    }
}
Enter fullscreen mode Exit fullscreen mode

Without autoboxing, we would have to write extra code every time to convert values.

Small thing to watch out for

If you try to unbox a null value, it will cause an error.

Integer obj = null;
int x = obj;
Enter fullscreen mode Exit fullscreen mode

This will throw a NullPointerException. So it’s better to check before using it.

Final note

Autoboxing and unboxing might look like small features, but they actually make coding much easier. Especially when working with collections, this becomes really helpful.

Once you understand this, a lot of things in Java start to make more sense.

Source: dev.to

arrow_back Back to Tutorials