Junior — Middle
Explain the concept of a wrapper class for primitive data types.
sobes.tech AI
Answer from AI
A wrapper class in Java is a class that encapsulates a primitive data type (such as int, boolean, char) into an object. This allows primitives to be used where objects are required, for example, in collections.
Java provides wrapper classes for all primitives:
IntegerforintBooleanforbooleanCharacterforchar- and so on.
Advantages:
- They allow primitives to be used in collections that only work with objects (e.g.,
ArrayList<Integer>). - They provide methods for conversion and working with primitives.
Example:
int a = 5;
Integer aWrapper = Integer.valueOf(a); // boxing
int b = aWrapper.intValue(); // unboxing
ArrayList<Integer> list = new ArrayList<>();
list.add(a); // auto-boxing: int is automatically boxed into Integer
Thus, wrapper classes provide object-oriented handling of primitive types.