Java.Core.What is autoboxing in Java and what are the rules for boxing primitive types in wrapper classes?

Autoboxing in Java

Autoboxing is the automatic conversion of primitive data types into their corresponding wrapper classes when required.

Example of Autoboxing:

public class AutoboxingExample {
    public static void main(String[] args) {
        int primitiveInt = 10;
        Integer wrappedInt = primitiveInt; // Autoboxing
        System.out.println(wrappedInt); // Output: 10
    }
}

👉 Here, primitiveInt (int) is automatically converted to Integer (wrapper class).

Rules for Boxing Primitive Types in Wrapper Classes

Java provides a set of wrapper classes in java.lang package for each primitive type:

Primitive TypeWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Boxing Rules

  1. Implicit conversion (autoboxing) happens when assigning a primitive to a wrapper type variable.
Integer x = 10; // int to Integer (autoboxing)
Double y = 3.14; // double to Double (autoboxing)

2. Autoboxing occurs when passing a primitive to a method expecting a wrapper type.

public class BoxingExample {
    static void printNumber(Integer num) { // Method expects Integer
        System.out.println(num);
    }

    public static void main(String[] args) {
        int value = 50;
        printNumber(value); // Autoboxing (int → Integer)
    }
}

4. Autoboxing occurs when adding primitive values to collections (List, Set, etc.).

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

public class ListExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(5); // Autoboxing (int → Integer)
        System.out.println(numbers); // Output: [5]
    }
}

5. Autoboxing does not work for null with primitive types.

Integer num = null; // Allowed
int primitiveNum = num; // NullPointerException if num is null

Unboxing in Java

Unboxing is the automatic conversion of a wrapper class to its corresponding primitive type.

Example of Unboxing:

public class UnboxingExample {
    public static void main(String[] args) {
        Integer wrappedInt = 100;
        int primitiveInt = wrappedInt; // Unboxing
        System.out.println(primitiveInt); // Output: 100
    }
}

👉 Here, wrappedInt (Integer) is automatically converted to int.

Rules for Unboxing

  1. Wrapper class objects can be directly assigned to primitive types.
Integer obj = 20;
int num = obj; // Unboxing

2. Unboxing happens automatically when passing wrapper objects to methods expecting primitives.

public class UnboxingExample {
    static void printDouble(double value) {
        System.out.println(value);
    }

    public static void main(String[] args) {
        Double wrappedValue = 4.56;
        printDouble(wrappedValue); // Unboxing (Double → double)
    }
}

3. Unboxing occurs when performing arithmetic operations.

Integer x = 10;
Integer y = 5;
int sum = x + y; // Unboxing both x and y, then performing addition
System.out.println(sum); // Output: 15

4. Be careful with null values in wrapper classes (can cause NullPointerException).

Integer obj = null;
int num = obj; // Causes NullPointerException

Performance Considerations

  • Boxing and unboxing cause performance overhead because objects require more memory and processing than primitives.
  • Prefer using primitive types in performance-critical sections (e.g., loops, large calculations).

Example of Performance Issue

public class PerformanceTest {
    public static void main(String[] args) {
        long startTime = System.nanoTime();
        
        Integer sum = 0; // Wrapper type (boxing/unboxing overhead)
        for (int i = 0; i < 10_000_000; i++) {
            sum += i; // Unboxing and re-boxing in each iteration
        }

        long endTime = System.nanoTime();
        System.out.println("Time taken: " + (endTime - startTime) + " ns");
    }
}

👉 Using int instead of Integer can significantly improve performance.


Key Takeaways

FeatureAutoboxing (Primitive → Wrapper)Unboxing (Wrapper → Primitive)
DefinitionAutomatic conversion of a primitive to its wrapper classAutomatic conversion of a wrapper object to its primitive type
ExampleInteger x = 10; (intInteger)int y = x; (Integerint)
UsageAssigning primitive to wrapper, adding primitives to collections, passing to methods with wrapper parametersAssigning wrapper to primitive, passing to methods with primitive parameters, arithmetic operations
Performance ImpactSlightly slower than primitives (due to object creation)Slower than direct primitive operations
RiskNone (except minor performance overhead)Can cause NullPointerException if wrapper is null
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.