Java Wrapper Classes

Wrapper classes in Java provide a way to use primitive data types (int, char, etc.) as objects. Each primitive type has a corresponding wrapper class in the java.lang package.

1. List of Wrapper Classes

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

2. Autoboxing and Unboxing

Autoboxing is the automatic conversion of primitive types to their corresponding wrapper classes. Unboxing is the reverse process.

Example:

Integer num = 10; // Autoboxing: int to Integer
int n = num;        // Unboxing: Integer to int

3. Usage in Collections

Wrapper classes are necessary when working with collections that require objects, such as ArrayList.

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5); // Autoboxing

4. Common Methods

  • parseXxx(String s) - Parses a string into a primitive type (e.g., Integer.parseInt("123")).
  • valueOf(String s) - Returns an instance of the wrapper class.
  • xxxValue() - Converts the wrapper object to a primitive type (e.g., intValue()).

5. Key Takeaways

  • Wrapper classes convert primitives into objects.
  • Autoboxing and unboxing simplify conversions between primitives and wrappers.
  • Useful when working with collections and generics.
  • Provide utility methods for parsing and converting values.