Nearby lessons

48 of 125

Java - Wrapper Classes

📌 What You Will Learn
  • Why wrapper classes exist
  • How to convert primitive to object and object to primitive
  • Autoboxing and unboxing (automatic conversion)
  • Important methods: valueOf, parseXxx, toString, xxxValue
  • The famous Integer caching (range -128 to 127)

Wrapper Classes is a core concept of the Java language. This lesson explains Why Do We Need Wrapper Classes?, Converting Primitive to Object (Manually) and Autoboxing and Unboxing (Java 5 onwards) with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Why Do We Need Wrapper Classes?

Primitive types (int, char, boolean, etc.) are not objects. But many parts of Java work only with objects. For example, Collections (ArrayList, HashMap) can store only objects — they cannot store a raw int.

To solve this, Java provides wrapper classes — one class for each primitive type, which wraps the primitive value inside an object. Think of a wrapper class as a gift box: the primitive value (the gift) is inside the box (the object).

PrimitiveWrapper class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Converting Primitive to Object (Manually)

The old way (before Java 5) was to use the wrapper constructor or the valueOf method:

Example02
JCode Cell
1int a = 10;
2Integer i = Integer.valueOf(a); // box the primitive into an object
3System.out.println(i);

Autoboxing and Unboxing (Java 5 onwards)

From Java 5, this conversion became automatic:

  • Autoboxing — primitive to wrapper object, done automatically.
  • Unboxing — wrapper object to primitive, done automatically.
In simple words: Autoboxing and unboxing are automatic conversions done by the compiler. Integer i = 10; really writes Integer.valueOf(10), and int a = i; really writes i.intValue().
Example03
JCode Cell
1// Autoboxing: int -> Integer (automatic)
2Integer i = 10; // compiler writes Integer.valueOf(10)
3 
4// Unboxing: Integer -> int (automatic)
5int a = i; // compiler writes i.intValue()
6 
7// Works inside collections too
8ArrayList<Integer> list = new ArrayList<>();
9list.add(50); // autoboxed to Integer(50)
10int x = list.get(0); // unboxed back to int
11System.out.println(x);

Important Methods of Wrapper Classes

Wrapper classes give many useful static methods. Memorise these five families:

MethodPurposeExample
valueOf(String)Convert a String into a wrapper objectInteger.valueOf("100")
parseXxx(String)Convert a String into a primitiveInteger.parseInt("100") -> int 100
toString(xxx)Convert a primitive into StringInteger.toString(100) -> "100"
xxxValue()Convert wrapper to primitivei.intValue(), d.doubleValue()
MIN_VALUE / MAX_VALUERange constants of each typeInteger.MAX_VALUE
Trainer's Note: Classic interview question: what is the difference between parseInt and valueOf? parseInt("100") returns an int (primitive). valueOf("100") returns an Integer (object). One gives the gift, the other gives the gift in a box.
In simple words: `parseInt` returns a primitive `int`; `valueOf` returns an `Integer` object. Use parseInt when you need a number to calculate with, and valueOf when you need an object for a collection.
Example04
JCode Cell
1class WrapperMethods {
2 public static void main(String[] args) {
3 int x = Integer.parseInt("456"); // String -> int
4 double y = Double.parseDouble("45.67"); // String -> double
5 String s = Integer.toString(123); // int -> String
6 
7 Integer obj = Integer.valueOf("789"); // String -> Integer object
8 int back = obj.intValue(); // Integer -> int
9 
10 System.out.println(x + " " + y + " " + s + " " + back);
11 }
12}
Output
456 45.67 123 789

equals() vs == (Important for Wrappers)

With wrapper objects, == compares references (are they the same box?) while equals() compares values (is the gift inside same?). This leads to a famous surprise called Integer caching:

Why? Java caches Integer objects for the range -128 to +127. For these values it reuses the same object, so == is true. Outside this range, new objects are created each time, so == is false even though the values are equal.

Trainer's Note: Golden rule for beginners: always use `.equals()` to compare wrapper objects or Strings, never ==. Use == only for primitives.
In simple words: Always compare wrapper objects with `.equals()`, never with `==`. == checks whether two references point to the same box; .equals() checks whether the values inside are equal.
Example05
JCode Cell
1Integer a = 100;
2Integer b = 100;
3System.out.println(a == b); // true (cached, same box)
4 
5Integer c = 1000;
6Integer d = 1000;
7System.out.println(c == d); // false (not cached, different boxes)
8 
9System.out.println(c.equals(d)); // true (values are equal)
Output
true false true

Wrapper Methods Used Most in Real Code

Example06
JCode Cell
1class RealWorldUse {
2 public static void main(String[] args) {
3 // 1. Read a number from the command line (comes as String)
4 int age = Integer.parseInt(args[0]);
5 
6 // 2. Check ranges
7 System.out.println("Max int = " + Integer.MAX_VALUE);
8 
9 // 3. Work with characters
10 char ch = 'A';
11 System.out.println(Character.isDigit(ch)); // false
12 System.out.println(Character.isLetter(ch)); // true
13 System.out.println(Character.toUpperCase('a')); // A
14 }
15}
Output
Max int = 2147483647 false true A

The Six Conversions Between Primitive, Object and String

The classic material teaches all the conversion directions between the three worlds: primitive, wrapper object, and String. Master these six:

ConversionMethodExample
Primitive -> ObjectvalueOf() or constructorInteger.valueOf(10)
Object -> PrimitivexxxValue()i.intValue()
String -> ObjectvalueOf(String)Integer.valueOf("10")
Object -> StringtoString()i.toString()
Primitive -> StringString.valueOf() or toString()String.valueOf(10)
String -> PrimitiveparseXxx()Integer.parseInt("10")
Trainer's Note: The single toString() method appears twice in this table — Java uses one method name for both 'Object to String' and 'primitive to String'. That is why remembering these six directions makes every wrapper question easy.
Example07
JCode Cell
1class SixConversions {
2 public static void main(String[] args) {
3 int p = 10; // primitive
4 
5 Integer obj = Integer.valueOf(p); // primitive -> Object
6 int p2 = obj.intValue(); // Object -> primitive
7 
8 Integer obj2 = Integer.valueOf("20"); // String -> Object
9 String s1 = obj2.toString(); // Object -> String
10 String s2 = String.valueOf(p); // primitive -> String
11 int p3 = Integer.parseInt("30"); // String -> primitive
12 
13 System.out.println(p + " " + p2 + " " + obj2 + " " + s1 + " " + s2 + " " + p3);
14 }
15}
Output
10 10 20 20 10 30
📝 Key Takeaways
  • Wrapper classes box each primitive into an object: int->Integer, char->Character, etc.
  • Autoboxing converts primitive to wrapper automatically; unboxing does the reverse.
  • parseInt returns primitive int; valueOf returns Integer object.
  • Use equals() not == for wrapper objects and Strings.
  • Integer values from -128 to 127 are cached, so == can be true for small values.
  • Collections can store only objects, so wrappers are essential there.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2