DEV Community

Sudhakar V
Sudhakar V

Posted on

Wrapper Class In Java

In Java, a wrapper class is an object representation of one of the eight primitive data types. Wrapper classes live in the java.lang package and β€œwrap” a primitive value inside an immutable object. This allows primitives to be used in contexts that require objects (e.g., Java Collections, generics, reflection).


πŸ“¦ The Eight Wrapper Classes

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

⭐ Why Wrapper Classes?

  1. Collections & Generics – You cannot store primitives in Collection types; you must use objects. – e.g., List<Integer> vs. illegal List<int>.
  2. Utility Methods – Parsing from String (Integer.parseInt("42")). – Converting to String (Double.toString(3.14)). – Access to min/max constants (Integer.MAX_VALUE).
  3. Nullability – Objects can be null; primitives cannot. – Allows tri-state logic (e.g., Boolean can be true, false, or null).
  4. Reflection & Frameworks – Many libraries (e.g., JDBC, JSON mappers) expect objects rather than primitives.

πŸ”„ Autoboxing & Unboxing (Since Java 5)

  • Autoboxing: Automatic conversion from primitive β†’ wrapper.
  Integer i = 100;        // compiler turns into Integer.valueOf(100)
Enter fullscreen mode Exit fullscreen mode
  • Unboxing: Automatic conversion from wrapper β†’ primitive.
  int x = new Integer(50); // compiler converts to intValue()
Enter fullscreen mode Exit fullscreen mode

πŸ“‹ Common Methods

Method Description
valueOf(String s) Returns wrapper object holding parsed primitive value.
parseXxx(String s) Returns primitive (e.g., Integer.parseInt("123")).
toString() Returns String representation of the value.
xxxValue() Instance method to extract primitive (e.g., intValue()).
compareTo(W other) Compare two wrappers (Integer.compareTo()).
equals(Object obj) Equality check based on primitive value.
hashCode() Hash code derived from the wrapped value.

πŸ” Example Usage

import java.util.*;

public class WrapperExample {
    public static void main(String[] args) {
        // 1. Autoboxing in Collections
        List<Integer> numbers = new ArrayList<>();
        numbers.add(10);      // autoboxes int β†’ Integer.valueOf(10)
        numbers.add(20);

        // 2. Unboxing for arithmetic
        int sum = numbers.get(0) + numbers.get(1); // unboxes to int

        // 3. Parsing from String
        String input = "123";
        int parsed = Integer.parseInt(input);

        // 4. Nullability
        Boolean flag = null;   // allowed
        if (flag != null && flag) {
            System.out.println("Flag is true");
        }

        System.out.println("Sum = " + sum + ", parsed = " + parsed);
    }
}
Enter fullscreen mode Exit fullscreen mode

⚠️ Caching & Performance

  • Integer cache: Integer.valueOf(int) caches values in [-128, 127] to reuse objects.
  • Avoid excessive boxing/unboxing in hot loops:
  // slower: repeatedly creates/unboxes
  for (Integer i : list) { total += i; }

  // faster: work with primitives directly if possible
  int tmp = 0;
  for (int v : primitiveArray) { tmp += v; }
Enter fullscreen mode Exit fullscreen mode

βœ… When to Use

  • Collections and generics always require wrapper types.
  • Parsing, formatting, and utility constants are only on wrappers.
  • APIs that expect objects (e.g., reflection, frameworks) need wrappers.

Primitives still offer best performance; use wrappers only when object behavior is required.

Top comments (0)