Autoboxing and Unboxing

Automatic Conversion

Autoboxing: the compiler converts a primitive to its wrapper automatically. Unboxing: wrapper back to primitive.

Example

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

public class Main {
    public static void main(String[] args) {
        Integer boxed = 10;               // autoboxing: Integer.valueOf(10)
        int plain = boxed;                // unboxing: boxed.intValue()

        List<Integer> marks = new ArrayList<>();
        marks.add(85);                    // int -> Integer
        marks.add(92);

        int total = 0;
        for (int m : marks) {             // Integer -> int
            total += m;
        }
        System.out.println("boxed=" + boxed + ", plain=" + plain);
        System.out.println("Total marks: " + total);
    }
}

Output

boxed=10, plain=10
Total marks: 177

Performance Note

Boxing creates objects. In tight loops over millions of values, use primitives (int, long) or primitive arrays instead of List<Integer>.

Long sum = 0L;                       // slow: creates a new Long on every +=
for (long i = 0; i < 1_000_000; i++) {
    sum += i;
}

long fastSum = 0;                    // fast: no objects
for (long i = 0; i < 1_000_000; i++) {
    fastSum += i;
}