πŸš€ Wrapper Classes in Java β€” Complete Detailed Guide

Introduction

In Java, everything is object-oriented β€” but primitive data types like int, double, char, and boolean are not objects β˜•

This creates a problem.

What if we want to:

  • Store numbers inside a collection like ArrayList? πŸ“¦
  • Convert numbers into strings? πŸ”„
  • Use utility methods like parsing and comparison?
  • Treat primitive values as objects?

To solve this, Java provides Wrapper Classes 🎯

Wrapper classes allow primitive data types to be used as objects.

Let’s understand this concept in detail.


🧠 What Are Wrapper Classes?

A Wrapper Class is a class that wraps (encloses) a primitive data type inside an object.

Each primitive type has a corresponding wrapper class.


πŸ“Š Primitive Types and Their Wrapper Classes

PrimitiveWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

🎯 Why Do We Need Wrapper Classes?

Primitive types:

  • ❌ Are not objects
  • ❌ Cannot be stored in collections directly
  • ❌ Do not have methods

Wrapper classes:

  • βœ… Are objects
  • βœ… Can be stored in collections
  • βœ… Provide useful methods

🟒 Example 1: Using Integer Wrapper

public class WrapperDemo1 {
    public static void main(String[] args) {

        int num = 10;

        Integer obj = Integer.valueOf(num);

        System.out.println("Primitive value: " + num);
        System.out.println("Wrapper object: " + obj);
    }
}

🧠 Step-by-Step Explanation

  • num is primitive
  • Integer.valueOf(num) converts primitive into object
  • obj is an Integer object

This process is called Boxing πŸ“¦


πŸ”„ Boxing and Unboxing


πŸ“¦ Boxing

Converting primitive β†’ object

int a = 20;
Integer obj = Integer.valueOf(a);

πŸ“€ Unboxing

Converting object β†’ primitive

Integer obj = 30;
int a = obj.intValue();

✨ Autoboxing and Auto-Unboxing

Since Java 5, conversion happens automatically.


🟒 Example 2: Autoboxing

public class AutoBoxingDemo {
    public static void main(String[] args) {

        int num = 50;

        Integer obj = num;   // Autoboxing

        System.out.println(obj);
    }
}

🟒 Example 3: Auto-Unboxing

public class AutoUnboxingDemo {
    public static void main(String[] args) {

        Integer obj = 100;

        int num = obj;   // Auto-unboxing

        System.out.println(num);
    }
}

πŸ“¦ Wrapper Classes in Collections

Collections like ArrayList store objects only.


🟒 Example 4: Using ArrayList

import java.util.ArrayList;

public class CollectionDemo {
    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>();

        list.add(10);
        list.add(20);
        list.add(30);

        System.out.println(list);
    }
}

🧠 Explanation

  • ArrayList<Integer> stores Integer objects
  • 10 is autoboxed automatically

Primitive int cannot be stored directly ❌


πŸ”’ Important Wrapper Class Methods


πŸ“Œ Integer Methods

Integer.parseInt("123");   // String β†’ int
Integer.toString(100);     // int β†’ String
Integer.max(10, 20);       // Maximum value

🟒 Example 5: Parsing String

public class ParseDemo {
    public static void main(String[] args) {

        String str = "200";

        int num = Integer.parseInt(str);

        System.out.println(num + 50);
    }
}

🧠 Explanation

  • Converts string to integer
  • Useful for user input handling

πŸ”Ž Comparing Wrapper Objects


❗ Important Concept

Integer a = 100;
Integer b = 100;

System.out.println(a == b);

This may return true because of Integer caching.

But:

Integer a = 200;
Integer b = 200;

System.out.println(a == b);

This may return false.

πŸ“Œ Always use:

a.equals(b);

❌ Common Mistakes

❌ Using == for comparison

if(a == b) // Wrong

Use:

if(a.equals(b))

❌ NullPointerException during unboxing

Integer obj = null;
int num = obj;  // ❌ Runtime error

❌ Forgetting parsing exception

Integer.parseInt("abc");  // NumberFormatException

🧠 Memory Concept

  • Primitive stored in stack
  • Wrapper objects stored in heap

Autoboxing creates object in heap memory.


🎯 When Should You Use Wrapper Classes?

βœ” When working with collections
βœ” When converting String to numbers
βœ” When using utility methods
βœ” When null values are required
βœ” When working with generics


πŸ“Œ Wrapper vs Primitive

PrimitiveWrapper
FasterSlightly slower
No methodsHas methods
Stored in stackStored in heap
Cannot store nullCan store null

πŸ”₯ Interview/Viva Important Points

  • Wrapper classes are immutable
  • Integer caching occurs between -128 to 127
  • Autoboxing introduced in Java 5
  • Collections work only with objects

πŸ§ͺ Tricky Example

public class TrickyWrapper {
    public static void main(String[] args) {

        Integer a = 127;
        Integer b = 127;

        System.out.println(a == b);  // true

        Integer x = 128;
        Integer y = 128;

        System.out.println(x == y);  // false
    }
}

🧠 Why?

Java caches Integer values between -128 and 127.

Beyond that range, new objects are created.


βœ… Conclusion

Wrapper classes bridge the gap between primitive data types and objects in Java πŸš€

They allow:

  • Object-based manipulation of primitive values
  • Storage in collections
  • Easy conversion between data types
  • Access to useful utility methods

Understanding wrapper classes deeply improves:

  • Collection usage
  • Data handling
  • Input processing
  • Memory understanding

Mastering this topic strengthens your core Java foundation and prepares you for advanced concepts πŸ’ͺ

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *