Sobes.tech
Junior

What are wrapper classes in Java?

sobes.tech AI

Answer from AI

Wrapper classes in Java are classes that represent primitive data types as objects. They provide a set of useful methods for working with the corresponding primitive values.

Main wrapper classes for primitive types:

  • byte -> Byte
  • short -> Short
  • int -> Integer
  • long -> Long
  • float -> Float
  • double -> Double
  • char -> Character
  • boolean -> Boolean

Advantages of using wrapper classes:

  • Working with primitive types in collections (ArrayList, HashMap, etc.), which can only store objects.
  • Providing methods for type conversion (e.g., string to number).
  • Supporting null values (primitive types cannot be null).
  • Usage in Reflection API and other frameworks that work with objects.

Java provides autoboxing and unboxing mechanisms that automatically convert primitive types to their wrapper objects and vice versa.

Example of autoboxing and unboxing:

// Autoboxing: int to Integer
Integer wrapperInt = 10;

// Unboxing: Integer to int
int primitiveInt = wrapperInt;