Java Wrapper Classes
Java's type system has a clear divide between primitive types and objects. Primitives are fast and memory-efficient but cannot be used where objects are re...
Bridging Primitives and Objects with Wrapper Classes
Java's type system has a clear divide between primitive types and objects. Primitives are fast and memory-efficient but cannot be used where objects are required — for example, as elements in a generic collection like ArrayList<Integer>. Wrapper classes bridge this gap by providing an object representation for each of the eight primitive types.
The eight wrapper classes, found in the java.lang package, are: Byte for byte, Short for short, Integer for int, Long for long, Float for float, Double for double, Character for char, and Boolean for boolean. Notice that Integer and Character do not simply add a capital letter to the primitive name; the others do follow that pattern.
Autoboxing is the automatic conversion of a primitive to its corresponding wrapper class. Unboxing is the reverse — the automatic extraction of a primitive value from a wrapper object. These conversions are performed silently by the Java compiler. For example: Integer obj = 42; is autoboxing (the int literal 42 is wrapped in an Integer). int x = obj; is unboxing (the Integer is unpacked to int). This feature, introduced in Java 5, greatly reduced boilerplate code when working with collections.
Wrapper classes provide many useful static utility methods. Integer.parseInt(String s) converts a string to an int. Integer.toBinaryString(n), Integer.toOctalString(n), and Integer.toHexString(n) convert integers to different base representations. Integer.MAX_VALUE and Integer.MIN_VALUE give the largest and smallest possible int values (2147483647 and -2147483648 respectively). Double.isNaN(d) checks whether a double value is Not-a-Number. Character.isDigit(c), Character.isLetter(c), and Character.toUpperCase(c) provide character classification and conversion utilities.
Wrapper objects are immutable. Once an Integer object is created holding the value 5, it will always hold 5. Apparent modifications like obj = obj + 1 actually create a new Integer object.
Integer caching is an important implementation detail: the JVM caches Integer objects for values between -128 and 127. This means Integer a = 127; Integer b = 127; a == b evaluates to true (same cached object), but Integer a = 200; Integer b = 200; a == b evaluates to false (different objects). Always use .equals() to compare wrapper objects for value equality.
Interview tip: Unboxing a null wrapper reference causes a NullPointerException. For example, Integer i = null; int x = i; throws a NullPointerException at runtime. This is one of the most common sources of NullPointerExceptions in code that uses autoboxing carelessly with nullable values from database queries or external APIs.