← Back to Core Java Course | Chapter 14: Advanced Topics | Lesson 1 of 6

Java Wrapper Classes

What are Wrapper Classes

Wrapper classes like Integer, Double, and Boolean provide object equivalents of Java's primitive types, letting primitives be used anywhere an Object is required — such as inside generic collections.

Example: What are Wrapper Classes

java
import java.util.ArrayList;
public class Main {
	public static void main(String[] args) {
		ArrayList<Integer> numbers = new ArrayList<>(); // Integer wraps int
		numbers.add(5);
		System.out.println(numbers.get(0));
	}
}

Understanding Autoboxing

Autoboxing is Java automatically converting a primitive into its wrapper type when an object is expected, like assigning an int directly to an Integer variable without an explicit cast.

Example: Understanding Autoboxing

java
public class Main {
	public static void main(String[] args) {
		Integer boxed = 5; // int automatically becomes Integer
		System.out.println(boxed);
	}
}

Understanding Unboxing

Unboxing is the reverse: Java automatically extracts the primitive value from a wrapper object when a primitive is expected, such as using an Integer in an arithmetic expression.

Example: Understanding Unboxing

java
public class Main {
	public static void main(String[] args) {
		Integer boxed = 10;
		int primitive = boxed + 5; // Integer automatically becomes int
		System.out.println(primitive);
	}
}

Parsing Numeric Strings

Methods like Integer.parseInt() and Double.parseDouble() convert a String into its corresponding primitive value, throwing NumberFormatException if the string isn't a valid number.

Example: Parsing Numeric Strings

java
public class Main {
	public static void main(String[] args) {
		int num = Integer.parseInt("42");
		double d = Double.parseDouble("3.14");
		System.out.println(num + " " + d);
	}
}

Wrapper Constants and Utility Methods

Wrapper classes also expose useful constants and utilities, like Integer.MAX_VALUE for the largest representable int, and Integer.compare() for a null-safe comparison alternative to </>.

Example: Wrapper Constants and Utility Methods

java
public class Main {
	public static void main(String[] args) {
		System.out.println(Integer.MAX_VALUE);
		System.out.println(Integer.compare(3, 7));
	}
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.