Sobes.tech
Junior

What are wrapper classes in Java?

sobes.tech AI

Answer from AI

Wrappers (wrapper classes) in Java are classes from the java.lang package that represent primitive data types (byte, short, int, long, float, double, boolean, char) as objects.

Main features:

  • Object representation: They allow working with primitives as objects, which is necessary for using in collections (e.g., ArrayList, HashMap), frameworks that require objects, and when working with generics.
  • Methods availability: They have useful methods for type conversion, value manipulation, and comparison.
  • Auto-boxing/Auto-unboxing: Since Java 5, there is a mechanism for automatic conversion between primitive types and their wrappers (autoboxing/unboxing), simplifying code.

Examples of wrappers:

Primitive type Wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

Example of using auto-boxing/auto-unboxing:

// Auto-boxing: int -> Integer
Integer integerObject = 10; 

// Auto-unboxing: Integer -> int
int primitiveInt = integerObject; 

// Using in a collection
List<Integer> numbers = new ArrayList<>();
numbers.add(25); // Auto-boxing
int firstElement = numbers.get(0); // Auto-unboxing

They are used to ensure compatibility of primitive types with object-oriented structures and Java APIs.