Introduction
Wrapper classes convert primitive types to objects. Autoboxing is automatic conversion between primitive and wrapper.
Wrapper Classes
Each primitive has a corresponding wrapper class:
| Primitive | Wrapper Class |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
Why Wrapper Classes?
- Collections: ArrayList, HashMap need objects
- Null values: Primitives can’t be null
- Utility methods: parseInt(), toString(), etc.
- Generics: Type parameters need objects
// ✗ Can't use primitive in ArrayList
// ArrayList<int> list = new ArrayList<>();
// ✓ Use wrapper
ArrayList<Integer> list = new ArrayList<>();
Creating Wrapper Objects
Old Way (Before Java 9):
Integer num1 = new Integer(10); // Deprecated
Double num2 = new Double(3.14); // Deprecated
Boolean flag = new Boolean(true); // Deprecated
Modern Way:
Integer num1 = Integer.valueOf(10);
Double num2 = Double.valueOf(3.14);
Boolean flag = Boolean.valueOf(true);
// Or use autoboxing
Integer num3 = 10;
Double num4 = 3.14;
Boolean flag2 = true;
Autoboxing
Automatic conversion from primitive to wrapper.
public class Main {
public static void main(String[] args) {
// Autoboxing: int -> Integer
Integer num = 10; // Automatically converted
// Equivalent to:
Integer num2 = Integer.valueOf(10);
System.out.println(num); // 10
}
}
Unboxing
Automatic conversion from wrapper to primitive.
public class Main {
public static void main(String[] args) {
Integer num = 100;
// Unboxing: Integer -> int
int value = num; // Automatically converted
// Equivalent to:
int value2 = num.intValue();
System.out.println(value); // 100
}
}
Autoboxing in Collections
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
// Autoboxing: int -> Integer
numbers.add(10); // Automatically boxed
numbers.add(20);
numbers.add(30);
// Unboxing: Integer -> int
int first = numbers.get(0); // Automatically unboxed
System.out.println(first); // 10
}
}
Complete Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
// Autoboxing in loop
for (int i = 1; i <= 5; i++) {
numbers.add(i); // int -> Integer
}
// Unboxing in enhanced for loop
int sum = 0;
for (int num : numbers) { // Integer -> int
sum += num;
}
System.out.println("Numbers: " + numbers);
System.out.println("Sum: " + sum);
}
}
Integer Wrapper Methods
public class Main {
public static void main(String[] args) {
// String to int
int num1 = Integer.parseInt("123");
System.out.println(num1); // 123
// String to Integer
Integer num2 = Integer.valueOf("456");
System.out.println(num2); // 456
// int to String
String str1 = Integer.toString(789);
System.out.println(str1); // "789"
// Compare
int result = Integer.compare(10, 20);
System.out.println(result); // -1 (first < second)
// Max/Min values
System.out.println("Max: " + Integer.MAX_VALUE);
System.out.println("Min: " + Integer.MIN_VALUE);
// Binary, Octal, Hex
System.out.println("Binary: " + Integer.toBinaryString(10));
System.out.println("Octal: " + Integer.toOctalString(10));
System.out.println("Hex: " + Integer.toHexString(10));
}
}
Double Wrapper Methods
public class Main {
public static void main(String[] args) {
// String to double
double num1 = Double.parseDouble("3.14");
System.out.println(num1); // 3.14
// String to Double
Double num2 = Double.valueOf("2.718");
System.out.println(num2); // 2.718
// double to String
String str = Double.toString(1.414);
System.out.println(str); // "1.414"
// Compare
int result = Double.compare(3.14, 2.718);
System.out.println(result); // 1 (first > second)
// Max/Min values
System.out.println("Max: " + Double.MAX_VALUE);
System.out.println("Min: " + Double.MIN_VALUE);
// Special values
System.out.println("Infinity: " + Double.POSITIVE_INFINITY);
System.out.println("NaN: " + Double.NaN);
// Check
System.out.println("Is infinite: " + Double.isInfinite(1.0/0));
System.out.println("Is NaN: " + Double.isNaN(0.0/0));
}
}
Boolean Wrapper
public class Main {
public static void main(String[] args) {
// String to boolean
boolean b1 = Boolean.parseBoolean("true");
boolean b2 = Boolean.parseBoolean("false");
boolean b3 = Boolean.parseBoolean("yes"); // false (not "true")
System.out.println(b1); // true
System.out.println(b2); // false
System.out.println(b3); // false
// Boolean to String
String s1 = Boolean.toString(true);
System.out.println(s1); // "true"
// Compare
int result = Boolean.compare(true, false);
System.out.println(result); // 1
}
}
Character Wrapper
public class Main {
public static void main(String[] args) {
char ch = 'A';
// Check character type
System.out.println(Character.isDigit('5')); // true
System.out.println(Character.isLetter('A')); // true
System.out.println(Character.isUpperCase('A')); // true
System.out.println(Character.isLowerCase('a')); // true
System.out.println(Character.isWhitespace(' ')); // true
// Convert case
System.out.println(Character.toUpperCase('a')); // A
System.out.println(Character.toLowerCase('A')); // a
// Get numeric value
System.out.println(Character.getNumericValue('5')); // 5
}
}
Autoboxing in Methods
public class Main {
// Method accepts Integer
static void display(Integer num) {
System.out.println("Number: " + num);
}
// Method returns Integer
static Integer getNumber() {
return 100; // Autoboxing: int -> Integer
}
public static void main(String[] args) {
// Autoboxing: int -> Integer
display(50);
// Unboxing: Integer -> int
int value = getNumber();
System.out.println(value);
}
}
null and Unboxing (NullPointerException)
public class Main {
public static void main(String[] args) {
Integer num = null;
// ✗ NullPointerException when unboxing
// int value = num; // Crash!
// ✓ Check null first
if (num != null) {
int value = num;
System.out.println(value);
} else {
System.out.println("num is null");
}
}
}
Caching
Wrapper classes cache small values for performance.
public class Main {
public static void main(String[] args) {
// Cached (-128 to 127)
Integer a = 100;
Integer b = 100;
System.out.println(a == b); // true (same object)
// Not cached (outside range)
Integer c = 200;
Integer d = 200;
System.out.println(c == d); // false (different objects)
// ✓ Always use equals() for comparison
System.out.println(c.equals(d)); // true
}
}
Conversion Methods
public class Main {
public static void main(String[] args) {
Integer num = 100;
// Wrapper to primitive
int intValue = num.intValue();
double doubleValue = num.doubleValue();
long longValue = num.longValue();
float floatValue = num.floatValue();
System.out.println("int: " + intValue);
System.out.println("double: " + doubleValue);
System.out.println("long: " + longValue);
System.out.println("float: " + floatValue);
}
}
Real-World Example: Input Processing
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> scores = new ArrayList<>();
System.out.println("Enter 5 scores:");
for (int i = 0; i < 5; i++) {
String input = sc.nextLine();
try {
// String to int (autoboxing to Integer)
int score = Integer.parseInt(input);
scores.add(score);
} catch (NumberFormatException e) {
System.out.println("Invalid input, try again");
i--;
}
}
// Calculate average (unboxing)
int sum = 0;
for (int score : scores) {
sum += score;
}
double average = sum / (double) scores.size();
System.out.println("Scores: " + scores);
System.out.println("Average: " + average);
sc.close();
}
}
Performance Consideration
public class Main {
public static void main(String[] args) {
long start, end;
// Using primitives (faster)
start = System.nanoTime();
long sum1 = 0;
for (int i = 0; i < 1000000; i++) {
sum1 += i;
}
end = System.nanoTime();
System.out.println("Primitive time: " + (end - start) + "ns");
// Using wrappers (slower due to boxing/unboxing)
start = System.nanoTime();
Long sum2 = 0L;
for (int i = 0; i < 1000000; i++) {
sum2 += i; // Unboxing, addition, boxing
}
end = System.nanoTime();
System.out.println("Wrapper time: " + (end - start) + "ns");
}
}
Common Use Cases
1. Collections:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10); // Autoboxing
2. Null Values:
Integer age = null; // Can be null
// int age = null; // ✗ Error
3. Parsing Strings:
int num = Integer.parseInt("123");
double value = Double.parseDouble("3.14");
4. Utility Methods:
String binary = Integer.toBinaryString(10);
int max = Integer.MAX_VALUE;
Wrapper Class Hierarchy
Object
|
Number (abstract)
/ | | \
Byte Short Integer Long Float Double
Object
|
Character
Object
|
Boolean
Quick Reference
// Autoboxing
Integer num = 10; // int -> Integer
Double d = 3.14; // double -> Double
Boolean flag = true; // boolean -> Boolean
// Unboxing
int i = num; // Integer -> int
double value = d; // Double -> double
boolean b = flag; // Boolean -> boolean
// Parsing
int x = Integer.parseInt("123");
double y = Double.parseDouble("3.14");
boolean z = Boolean.parseBoolean("true");
// To String
String s1 = Integer.toString(123);
String s2 = Double.toString(3.14);
// Compare
Integer.compare(10, 20); // -1, 0, or 1
// Constants
Integer.MAX_VALUE
Integer.MIN_VALUE
Double.NaN
Double.POSITIVE_INFINITY
Common Mistakes
Mistake 1: Using == for Wrappers
Integer a = 200;
Integer b = 200;
// System.out.println(a == b); // ✗ false (different objects)
System.out.println(a.equals(b)); // ✓ true
Mistake 2: NullPointerException
Integer num = null;
// int x = num; // ✗ NullPointerException
if (num != null) {
int x = num; // ✓ Safe
}
Mistake 3: Unnecessary Boxing/Unboxing
// ✗ Inefficient
Integer sum = 0;
for (int i = 0; i < 1000; i++) {
sum += i; // Boxing and unboxing each time
}
// ✓ Efficient
int sum = 0;
for (int i = 0; i < 1000; i++) {
sum += i; // No boxing/unboxing
}
Integer result = sum; // Box once at end
Exam Tips
Remember:
- Wrapper classes convert primitives to objects
- Autoboxing: primitive → wrapper (automatic)
- Unboxing: wrapper → primitive (automatic)
- Use wrappers in collections
- parseInt() for String to primitive
- valueOf() for String to wrapper
- Always use equals() to compare wrappers
- NullPointerException when unboxing null
- Caching for small values (-128 to 127)
- Primitives faster than wrappers
Common Questions:
- What are wrapper classes?
- List all wrapper classes?
- What is autoboxing?
- What is unboxing?
- Why use wrapper classes?
- How to convert String to int?
- Difference between parseInt() and valueOf()?
- Why not use == for wrapper comparison?
- What is wrapper class caching?
- Performance impact of boxing/unboxing?