Java Wrapper Classes

📦 Java Wrapper Classes

Wrapper Classes in Java are object representations of primitive data types.

  • They allow primitive types (int, double, etc.) to be used as objects.

  • Package: java.lang

  • Used in Collections, Generics, and utility methods that require objects.


✅ 1. Primitive vs Wrapper Classes

Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

✅ 2. Why Use Wrapper Classes?

  1. Collections: Collections like ArrayList can only store objects, not primitives.

  2. Utility Methods: Wrapper classes provide useful methods (e.g., parsing strings).

  3. Autoboxing and Unboxing: Automatic conversion between primitives and objects.


🔹 3. Autoboxing and Unboxing

  • Autoboxing: Primitive → Wrapper Object

  • Unboxing: Wrapper Object → Primitive

public class WrapperExample {
public static void main(String[] args) {
// Autoboxing
int num = 10;
Integer obj = num; // primitive int → Integer
System.out.println("Autoboxed: " + obj);
// Unboxing
Integer obj2 = new Integer(20);
int num2 = obj2; // Integer → int
System.out.println(“Unboxed: “ + num2);
}
}


🔹 4. Wrapper Class Methods

Parsing Strings to Primitives

public class ParseExample {
public static void main(String[] args) {
String strInt = "100";
String strDouble = "3.14";
int i = Integer.parseInt(strInt);
double d = Double.parseDouble(strDouble);

System.out.println(“Integer: “ + i);
System.out.println(“Double: “ + d);
}
}

Converting Wrapper to String

public class WrapperToString {
public static void main(String[] args) {
int num = 50;
String str = Integer.toString(num);
System.out.println("String value: " + str);
}
}

🔹 5. Some Useful Methods

Wrapper Class Useful Methods
Integer parseInt(), valueOf(), toString(), MAX_VALUE, MIN_VALUE
Double parseDouble(), valueOf(), toString(), MAX_VALUE, MIN_VALUE
Boolean parseBoolean(), valueOf(), toString()
Character isDigit(), isLetter(), toUpperCase(), toLowerCase()

✅ 6. Example: Using Wrapper Classes in Collections

import java.util.ArrayList;

public class WrapperInCollections {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();

// Autoboxing adds primitive int to ArrayList
numbers.add(10);
numbers.add(20);

// Unboxing retrieves primitive int
int num = numbers.get(0);
System.out.println(“Number: “ + num);
}
}

  • Collections cannot store primitives directly; Wrapper classes are required.


Summary

  • Wrapper Classes = Object form of primitives

  • Autoboxing & Unboxing make conversions seamless

  • Used in Collections, parsing, and utility methods

You may also like...