Sobes.tech
Junior

What are wrappers (Wrapper classes) in Java?

sobes.tech AI

Answer from AI

Wrapper classes in Java are classes that provide an object-oriented representation of primitive data types. They allow primitive values to be used in contexts where objects are required, such as in collections or when working with multithreading.

Main Wrapper classes:

  • Byte
  • Short
  • Integer
  • Long
  • Float
  • Double
  • Boolean
  • Character

Examples of usage:

Using primitive:

// Primitive type
int x = 10;

Using Wrapper class:

// Wrapper class
Integer y = new Integer(20); // Deprecated way of creating
Integer z = 30; // Autoboxing (automatic conversion of primitive to object)

Conversion between primitives and Wrapper objects:

  • Autoboxing: Automatic conversion of primitive to Wrapper object.
    // Autoboxing
    int primitiveInt = 100;
    Integer wrapperInt = primitiveInt;
    
  • Unboxing: Automatic conversion of Wrapper object to primitive.
    // Unboxing
    Integer wrapperInteger = new Integer(200);
    int primitiveInteger = wrapperInteger;
    

Advantages of Wrapper classes:

  • Working with collections: Collections (List, Set, Map) store only objects.
  • Working with null: Wrapper objects can have a null value, unlike primitives.
  • Providing useful methods: Wrapper classes have methods for converting strings, comparing values, etc. For example, Integer.parseInt(String s).
  • Working with generics: Generics work only with objects.

Disadvantages of Wrapper classes:

  • Memory consumption: Wrapper objects occupy more memory than primitives.
  • Performance reduction: Autoboxing and unboxing can slightly reduce performance.

Example of usage in a collection:

import java.util.ArrayList;
import java.util.List;

public class WrapperExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(10); // Autoboxing
        numbers.add(new Integer(20)); // Explicit object creation

        int firstNum = numbers.get(0); // Unboxing
        System.out.println(firstNum);
    }
}