Wrapper Classes
Overview
Java is an Object-Oriented language, but for extreme performance, it includes 8 primitive data types (int, double, char, etc.) that are NOT objects. However, Java's powerful Collections Framework (ArrayList, HashMap, Generics) ONLY works with Objects. Wrapper Classes act as a 'box' that wraps around a primitive value, converting it into a full-fledged Object so it can be used in advanced Java features.
Syntax
Wrapper classes provide dozens of highly useful static methods to manipulate data, parse strings, and find max/min values.
// Primitive -> Wrapper Class
// byte -> Byte
// short -> Short
// int -> Integer
// long -> Long
// float -> Float
// double -> Double
// char -> Character
// boolean -> Boolean
// You cannot do this: List<int> numbers = new ArrayList<>();
// You MUST do this:
List<Integer> numbers = new ArrayList<>();Whenever you read JSON, XML, or URL parameters, everything comes in as a String. Wrapper classes are the tool you use to convert that text into usable math variables.
// Parsing a String into a primitive (Extremely common in web apps)
int age = Integer.parseInt("25");
double price = Double.parseDouble("19.99");
// Converting primitive back to String
String strAge = Integer.toString(age);
// Finding Min/Max
int max = Integer.MAX_VALUE; // 2147483647
int maxOfTwo = Integer.max(10, 50); // 50
// Character utilities
boolean isDigit = Character.isDigit('7'); // true
boolean isLetter = Character.isLetter('A'); // trueCommon Pitfalls
- Comparing Wrapper objects using `==`. Because they are objects, `==` compares memory addresses, not the actual numbers. Always use `.equals()` to compare Wrappers.
- NumberFormatException: Calling `.parseInt("25a")` on a string that contains letters or spaces.
Interview Tips
- Explain that Wrappers allow primitive types to be used in Java's Collections Framework (which only accepts Objects).
Real-World Example
Whenever a backend controller receives a query parameter from a URL (e.g., `?page=5`), it arrives as a String. Wrappers convert it.
public class WebController {
public void getPage(String pageParam) {
int pageNumber = 1; // Default
if (pageParam != null) {
try {
// Converting URL string to math variable
pageNumber = Integer.parseInt(pageParam);
} catch (NumberFormatException e) {
System.out.println("Invalid page number provided.");
}
}
fetchDatabasePage(pageNumber);
}
}