Junior
What are wrapper classes in Java?
sobes.tech AI
Answer from AI
In Java, wrapper classes provide object representations of primitive data types. There is a corresponding wrapper class for each primitive type:
boolean⇒Booleanchar⇒Characterbyte⇒Byteshort⇒Shortint⇒Integerlong⇒Longfloat⇒Floatdouble⇒Double
The main purposes of wrapper classes:
- Using primitive types in collections (e.g.,
ArrayList,HashMap), which only work with objects. - Providing useful methods for working with primitive types, such as parsing strings (
Integer.parseInt()) or comparison. - Supporting the concept of
null, which is absent in primitive types. - Autoboxing and unboxing - automatic conversion between primitives and their wrappers.
Example of autoboxing and unboxing:
// Autoboxing: int -> Integer
Integer wrapperInt = 10;
// Unboxing: Integer -> int
int primitiveInt = wrapperInt;
Example of usage in a collection:
import java.util.ArrayList;
// Collection of Integer objects
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(25); // Autoboxing
int firstNum = numbers.get(0); // Unboxing