Java Wrapper Classes
In this page:
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
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));
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
Integer boxed = 5; // int automatically becomes Integer
System.out.println(boxed);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
Integer boxed = 10;
int primitive = boxed + 5; // Integer automatically becomes int
System.out.println(primitive);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.compare(3, 7));
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: