Java's 8 primitive types provide raw computing performance, but they cannot participate in object-oriented structures like the Collections Framework (you cannot create ArrayList<int>). Wrapper classes wrap primitive values inside full-fledged Heap objects.
| Primitive Type | Wrapper Class (java.lang) | Parsing Method | Boxing Example |
|---|---|---|---|
byte | Byte | Byte.parseByte("10") | Byte b = 10; |
short | Short | Short.parseShort("20") | Short s = 20; |
int | Integer | Integer.parseInt("100") | Integer i = 100; |
long | Long | Long.parseLong("5000") | Long l = 5000L; |
float | Float | Float.parseFloat("3.14") | Float f = 3.14f; |
double | Double | Double.parseDouble("9.99") | Double d = 9.99; |
char | Character | N/A | Character c = 'A'; |
boolean | Boolean | Boolean.parseBoolean("true") | Boolean flag = true; |
import java.util.ArrayList;
public class AutoboxingDemo {
public static void main(String[] args) {
// Autoboxing: primitive int 42 automatically converted to Integer object
Integer numObj = 42;
// Unboxing: Integer object automatically converted back to primitive int
int primitiveNum = numObj;
// Collections require Objects:
ArrayList<Integer> list = new ArrayList<>();
list.add(100); // Autoboxed from int to Integer
int firstItem = list.get(0); // Unboxed from Integer to int
}
}
IntegerCache Trap (Interview Favorite)Java caches Integer objects within the range of -128 to 127. Notice what happens when you compare autoboxed objects with ==:
Integer a = 100;
Integer b = 100;
System.out.println(a == b); // TRUE! (Both point to cached instance)
Integer x = 200;
Integer y = 200;
System.out.println(x == y); // FALSE! (200 is outside cache; distinct Heap objects allocated!)
System.out.println(x.equals(y)); // TRUE! (Always use .equals() for objects!)
Exam Question: "What is the difference between Integer.parseInt("100") and Integer.valueOf("100")?"
Answer: Integer.parseInt() returns a raw primitive int. Integer.valueOf() returns an Integer object and utilizes the IntegerCache pool to save memory when possible.
Now let us explore the mathematical utilities of the Math class and pseudo-random numbers. Proceed to: Java Math Class & Random →
Accelerate your Java mastery by studying these tightly connected core tutorials:
The 8 primitive counterparts.
Storing wrapper objects in lists.
Why generics require wrapper objects.
Mathematical calculations.