Sobes.tech
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:

  • booleanBoolean
  • charCharacter
  • byteByte
  • shortShort
  • intInteger
  • longLong
  • floatFloat
  • doubleDouble

The main purposes of wrapper classes:

  1. Using primitive types in collections (e.g., ArrayList, HashMap), which only work with objects.
  2. Providing useful methods for working with primitive types, such as parsing strings (Integer.parseInt()) or comparison.
  3. Supporting the concept of null, which is absent in primitive types.
  4. 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