Wrapper class in Java

What is wrapper classes?
As the name suggests, a wrapper class wraps (encloses) around a data type and gives it an object appearance. Wherever, the data type is required as an object, this object can be used.

Wrapper class in java provides the mechanism to convert primitive into object and object into primitive. Wrapper classes are used to convert any data type into an object.

The primitive data types are not objects, they do not belong to any class. Sometimes, it is required to convert data types into objects and then needs to add them to collections. For such conversions, the Java introduced wrapper classes.

The 8 primitive types and its wrapper classes are,
byte - Byte
int - Integer
short - Short
long - Long
float - Float
double - Double
char - Character
boolean - Boolean

All this wrapper classes are available in java.lang package.

Wrapper Classes Hierarchy

What Is Autoboxing And Unboxing?
Autoboxing:
Automatic conversion of primitive types to the object of their corresponding wrapper classes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
//Java program to demonstrate Autoboxing
import java.util.ArrayList;

class Autoboxing {
 public static void main(String[] args) {
  char ch = 'a';
  ;

  // Autoboxing- primitive to Character object conversion
  Character a = ch;

  ArrayList<Integer> arrayList = new ArrayList<Integer>();

  // Autoboxing because ArrayList stores only objects
  arrayList.add(25);

  // printing the values from object
  System.out.println(arrayList.get(0));
 }
}

Unboxing:
It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
//Java program to demonstrate Unboxing

import java.util.ArrayList;

class Unboxing {
 public static void main(String[] args){
  Character ch = 'a';
  
  // unboxing - Character object to primitive conversion
  char a = ch;
  
  ArrayList<Integer> arrayList = new ArrayList<Integer>();
  arrayList.add(24);
  
  // unboxing because get method returns an Integer object
  int num = arrayList.get(0);

  // printing the values from primitive data types
  System.out.println(num);
 }
}

Why Wrapper Classes Were Introduced?
You can not directly put primitives into Collections, instead, you first need to convert them into Object and then only you can put them into Collections. Wrapper classes like Integer, Double and Boolean helps for converting primitive to Object.



<-- Previous || Next -->

1 comment: