Junior
What are wrappers (Wrapper classes) in Java?
sobes.tech AI
Answer from AI
Wrapper classes in Java are special classes that represent reference data types for primitive types. They allow working with primitives as objects.
Main features and purposes:
- Objects for primitives: Each primitive type (
byte,short,int,long,float,double,boolean,char) has a corresponding wrapper class (Byte,Short,Integer,Long,Float,Double,Boolean,Character). - Inheritance from
Object: All wrapper classes are descendants of theObjectclass, which allows their use in collections (such asArrayList,HashMap,HashSet) and other APIs that work with objects. - Fields and methods: Wrapper classes contain useful methods for working with the corresponding primitive values (e.g., string parsing, comparison). They also contain constants (e.g.,
Integer.MAX_VALUE,Integer.MIN_VALUE). - Autoboxing and unboxing: Java mechanisms that automatically convert between primitive types and their wrappers.
// Autoboxing Integer numObject = 10; // primitive int is automatically boxed into Integer // Unboxing int numPrimitive = numObject; // Integer object is automatically unboxed into primitive int - Immutability: Wrapper class objects are immutable. Their value cannot be changed after creation.
Integer a = 5; Integer b = a; // b references the same object a = 10; // a now references a new object with value 10, the object with 5 remains
Applications:
- Working with Java collections.
- Using in Stream API.
- Nullable values (the wrapper object can be
null, primitive — no). - Helper methods for type conversion and constants.
- In generics, which cannot work directly with primitive types.