Java
Beginner
1 min read
Wrapper Classes and Autoboxing
Example
import java.util.ArrayList;
import java.util.List;
public class AutoboxingDemo {
public static void main(String[] args) {
// --- Autoboxing: primitive -> wrapper (compiler inserts Integer.valueOf) ---
Integer boxed = 42; // equivalent to Integer.valueOf(42)
int unboxed = boxed; // equivalent to boxed.intValue()
// --- Wrapper utility methods ---
int parsed = Integer.parseInt("123");
int max = Integer.MAX_VALUE;
String bin = Integer.toBinaryString(255); // "11111111"
String hex = Integer.toHexString(255); // "ff"
System.out.printf("parsed: %d, max: %d%n", parsed, max);
System.out.printf("255 in binary: %s, hex: %s%n", bin, hex);
// --- Integer caching trap ---
Integer a = 127;
Integer b = 127;
Integer x = 200;
Integer y = 200;
System.out.println("127 == 127 (cached) : " + (a == b)); // true
System.out.println("200 == 200 (uncached): " + (x == y)); // false
System.out.println("200.equals(200) : " + x.equals(y)); // true
// --- NullPointerException from unboxing null ---
Integer nullInt = null;
try {
int boom = nullInt; // NullPointerException here
} catch (NullPointerException e) {
System.out.println("Caught NPE from unboxing null Integer");
}
// --- Autoboxing in collections ---
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
numbers.add(i); // autoboxed on add
}
int sum = 0;
for (int n : numbers) { // unboxed on retrieval
sum += n;
}
System.out.println("Sum 1-5: " + sum);
}
}