0
0
Javaprogramming~15 mins

Unboxing in Java

Choose your learning style8 modes available
menu_bookIntroduction

Unboxing is the automatic conversion of an object wrapper type to its corresponding primitive type. It helps you use objects like simple values easily.

When you have a wrapper object like Integer and want to use it as a simple int.
When performing arithmetic operations on wrapper objects.
When passing wrapper objects to methods that expect primitive types.
When comparing wrapper objects with primitive values.
When you want to simplify code by avoiding manual conversion.
regular_expressionSyntax
Java
int primitiveValue = wrapperObject;

Java automatically converts the wrapper object to its primitive type.

This works for all wrapper classes like Integer, Double, Boolean, etc.

emoji_objectsExamples
line_end_arrow_notchHere, the Integer object num is unboxed to the primitive int n.
Java
Integer num = 10;
int n = num;
line_end_arrow_notchThe Double object dObj is unboxed to the primitive double d.
Java
Double dObj = 5.5;
double d = dObj;
line_end_arrow_notchThe Boolean object flagObj is unboxed to the primitive boolean flag.
Java
Boolean flagObj = true;
boolean flag = flagObj;
code_blocksSample Program

This program shows how Integer and Double objects are automatically converted to primitive int and double types. Then it uses the unboxed values in calculations.

Java
public class UnboxingExample {
    public static void main(String[] args) {
        Integer wrappedInt = 100; // Integer object
        int primitiveInt = wrappedInt; // unboxing

        Double wrappedDouble = 12.34;
        double primitiveDouble = wrappedDouble; // unboxing

        System.out.println("Unboxed int: " + primitiveInt);
        System.out.println("Unboxed double: " + primitiveDouble);

        // Using unboxed values in arithmetic
        int sum = primitiveInt + 50;
        System.out.println("Sum: " + sum);
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

If the wrapper object is null, unboxing will cause a NullPointerException.

line_end_arrow_notch

Unboxing makes code cleaner by removing the need for explicit method calls like intValue().

list_alt_checkSummary

Unboxing converts wrapper objects to primitive types automatically.

It works with all wrapper classes like Integer, Double, Boolean, etc.

Be careful to avoid unboxing null objects to prevent errors.