Wrapper Class in Java – Learn Autoboxing & Unboxing with Coding Examples

Java is not a purely object-oriented programming language, the reason being it works on primitive data types. These eight primitive data types int, short, byte, long, float, double, char and, boolean are not objects. We use wrapper classes to use these data types in the form of objects. Wrapper class in Java makes the Java code fully object-oriented. For example, converting an int to Integer. Here int is a data type and Integer is the wrapper class of int.

We will discuss the concept of wrapper classes in Java with the examples. There are several reasons why we prefer a wrapper class instead of a primitive type; we will discuss them as well in this article. We will also discuss Autoboxing and Unboxing in Java.

Let’s take a quick revision on Data Types in Java to clear your basics with Techvidvan. 

Wrapper class in Java

Sometimes in the process of development, we come across situations where there is a need for objects instead of primitive data types. To achieve this, Java provides a concept of Wrapper classes. A Wrapper class in Java is the type of class that provides a mechanism to convert the primitive data types into the objects and vice-versa.

When a wrapper class is created, there is a creation of a new field in which we store the primitive data types. The object of the wrapper class wraps or holds its respective primitive data type.

The process of converting primitive data types into an object is called boxing. While using a wrapper class, you just have to pass the value of the primitive data type to the constructor of the Wrapper class.

All the wrapper classes Byte, Short, Integer, Long, Double and, Float, are subclasses of the abstract class Number. While Character and Boolean wrapper classes are the subclasses of class Object.

The diagram below shows the hierarchy of the wrapper classes.

Java Wrapper Class Hierarchy

Primitive Data TypeWrapper ClassConstructor Argument
booleanBooleanboolean or String
byteBytebyte or String
charCharacterchar
intIntegerint or String
floatFloatfloat, double or String
doubleDoubledouble or String
longLonglong or String
shortShortshort or String

Need for Wrapper class in Java

  • Wrapper classes are used to provide a mechanism to ‘wrap’ or bind the values of primitive data types into an object. This helps primitives types act like objects and do the activities reserved for objects like we can add these converted types to the collections like ArrayList, HashSet, HashMap, etc.
  • Wrapper classes are also used to provide a variety of utility functions for primitives data types like converting primitive types to string objects and vice-versa, converting to various bases like binary, octal or hexadecimal, or comparing various objects.
  • We can not provide null values to Primitive types but wrapper classes can be null. So wrapper classes can be used in such cases we want to assign a null value to primitive data types.

Advantages of using Wrapper class in Java

Java Wrapper Class Advantages

1. Serialization: In Serialization, We need to convert the objects into streams. If we have a primitive value and we want to serialize them then we can do this by converting them with the help of wrapper classes.

2. Synchronization: In Multithreading, Java synchronization works with objects.

3. java.util package: The package java.util provides many utility classes to deal with objects rather than values.

4. Collection Framework: The Collection Framework in Java works only with objects. All classes of the collection framework like ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc, work only with objects.

5. Changing the value inside a Method: So, if we pass a primitive value using call by value, it will not change the original value. But, it will change the original value if we convert the primitive value into an object.

6. Polymorphism: Wrapper classes also help in achieving Polymorphism in Java.

Get to know about Java Polymorphism in detail with Techvidvan.

Creating Wrapper Objects

We use the wrapper class to create an object of the wrapper class. To get the value of the data type, we can just print the object.

Code to illustrate the creation of Wrapper Objects:

package com.techvidvan.wrapperclasses;
public class WrapperDemo
{
  public static void main(String[] args)
  {
    Integer myInt = 10;
    Double myDouble = 11.65;
    Character myChar = 'T';
    Boolean myBool= true;

    System.out.println(myInt);
    System.out.println(myDouble);
    System.out.println(myChar);
    System.out.println(myBool);
  }
}

Output:

10
11.65
T
true

Autoboxing and Unboxing in Java

1. Autoboxing

The process to automatically convert the primitive data types into corresponding wrapper class objects is called Autoboxing in Java. This is Autoboxing because this is done automatically by the Java compiler. For example, char to Character, int to Integer, long to Long, double to Double, float to Float, boolean to Boolean, byte to Byte, and short to Short.

Code to understand Autoboxing in Java:

package com.techvidvan.wrapperclasses;
import java.util.ArrayList;
public class AutoboxingExample
{
  public static void main(String[] args)
  {
    //Converting an int primitive data type into an Integer object
    int number = 15;
    Integer obj=Integer.valueOf(number); //converting int into Integer explicitly
    System.out.println(number+ " "+ obj);

    //Converting char primitive data type into a Character object
    char character = 'a';
    Character obj1 = character;
    System.out.println(character+ " "+ obj1);

    //Using Collection Framework
    ArrayList<Integer> arrayList = new ArrayList<Integer>();
    arrayList.add(16); //Autoboxing
    arrayList.add(35); //Autoboxing
    System.out.println(arrayList.get(0));
    System.out.println(arrayList.get(1));
  }
}

Output:

15 15
a a
16
35

As you can see both primitive data types and objects have the same values. You can use obj in place of num wherever you need to pass the value of num as an object.

2. Unboxing

Java Unboxing is the reverse process of Autoboxing. The process to convert the wrapper class object into its corresponding primitive data type is called Java Unboxing.

Code to understand Unboxing in Java:

package com.techvidvan.wrapperclasses;
import java.util.ArrayList;
public class UnboxingExample
{
  public static void main(String[] args)
  {
    Character character = 'R'; //Autoboxing
    char value = character; //Unboxing
    System.out.println(value);

    ArrayList<Integer> arrayList = new ArrayList<Integer>();
    //Autoboxing
    arrayList.add(50);
    //Unboxing object into int value
    int num = arrayList.get(0);
    System.out.println(num);
  }
}

Output:

R
50

Implementing Wrapper class in Java

package com.techvidvan.wrapperclasses;
public class WapperClassDemo
{
  public static void main(String[] args)
  {
    // byte data type
    byte byteVar = 5;
    // wrapping around Byte object
    Byte byteobj = new Byte(byteVar);

    // int data type
    int intVar = 33;
    //wrapping around Integer object
    Integer intobj = new Integer(intVar);

    // float data type
    float floatVar = 16.8f;
    // wrapping around Float object
    Float floatobj = new Float(floatVar);

    // double data type
    double doubleVar = 496.87;
    // Wrapping around Double object
    Double doubleobj = new Double(doubleVar);

    // char data type
    char charVar='s';
    // wrapping around Character object
    Character charobj=charVar;

    // printing the values from objects
    System.out.println("Values of Wrapper objects (printing as objects)");
    System.out.println("Byte object byteobj: " + byteobj);
    System.out.println("Integer object intobj: " + intobj);
    System.out.println("Float object floatobj: " + floatobj);
    System.out.println("Double object doubleobj: " + doubleobj);
    System.out.println("Character object charobj: " + charobj);

    // objects to data types (retrieving data types from objects)
    // unwrapping objects to primitive data types
    byte unwrappingByte = byteobj;
    int unwrappingInt = intobj;
    float unwrappingFloat = floatobj;
    double unwrappingDouble = doubleobj;
    char unwrappingChar = charobj;

    System.out.println("Unwrapped values ");
    System.out.println("byte value, unwrapped Byte: " + unwrappingByte);
    System.out.println("int value, unwrapped Int: " + unwrappingInt);
    System.out.println("float value, unwrapped Float: " + unwrappingFloat);
    System.out.println("double value, unwrapped Double: " + unwrappingDouble);
    System.out.println("char value, unwrapped Char: " + unwrappingChar);
  }
}

Output:

Values of Wrapper objects (printing as objects)
Byte object byteobj: 5
Integer object int obj: 33
Float object floatobj: 16.8
Double object double bj: 496.87
Character object charobj: s
Unwrapped values
byte value, unwrapped Byte: 5
int value, unwrapped Int: 33
float value, unwrapped Float: 16.8
double value, unwrapped Double: 496.87
char value, unwrapped Char: s

Methods of Wrapper Class in Java

The following is the list of some methods that all the subclasses of the Number class implements:

S.No.Method Method Description
1.typeValue()Returns the Converted value of this Number object to the specified data type.
2.compareTo()It compares this Number object to the specified argument.
3.equals()It checks whether this Number object is equal to the specified argument.
4.valueOf()Returns an Integer object holding the specified primitive type value.
5.toString()Returns a String object holding the value of a specified Integer type argument.
6.parseInt()Retrieves the primitive data type of a specified String.
7.abs()Returns the absolute value of the specified argument.
8.ceil()Returns the smallest integer that is equal to or greater than the specified argument in double format.
9.floor()Returns the largest integer that is equal to or less than the specified argument in double format.
10.round()Returns the closest long or int according to the return type of the method.
11.min()Returns the smaller between two arguments.
12.max()Returns the larger between the two arguments.
13.exp()Returns e to the power of the argument, i.e. base of the natural logarithms.
14.log()Returns the natural logarithm of the specified argument.
15.pow()Returns the result of the first argument raised to the power of the second argument.
16.sqrt()Returns the square root of the specified argument.
17.sin()Returns the value of sine of the specified double value.
18.cos()Returns the value of the cosine of the specified double value.
19.tan()Returns the value of the tangent of the specified double value.
20.asin()Returns the value of the arcsine of the specified double value.
21.acos()Returns the value of the arccosine of the specified double value.
22.atan()Returns the value of the arctangent of the specified double value.
23.toDegrees()Converts the value of the argument to degrees.
24.toRadians()Converts the value of the argument to radians.
25.random()This method returns a random number.

Code to illustrate some methods of wrapper class:

package com.techvidvan.wrapperclasses;
public class WrapperDemo
{
  public static void main (String args[])
  {
    Integer intObj1 = new Integer (25);
    Integer intObj2 = new Integer ("25");
    Integer intObj3= new Integer (35);

    //compareTo demo
    System.out.println("Comparing using compareTo Obj1 and Obj2: " + intObj1.compareTo(intObj2));
    System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj1.compareTo(intObj3));

    //Equals demo
    System.out.println("Comparing using equals Obj1 and Obj2: " + intObj1.equals(intObj2));
    System.out.println("Comparing using equals Obj1 and Obj3: " + intObj1.equals(intObj3));
    Float f1 = new Float("2.25f");
    Float f2 = new Float("20.43f");
    Float f3 = new Float(2.25f);
    System.out.println("Comparing using compare f1 and f2: " +Float.compare(f1,f2));
    System.out.println("Comparing using compare f1 and f3: " +Float.compare(f1,f3));

    //Addition of Integer with Float
    Float f = intObj1.floatValue() + f1;
    System.out.println("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+"=" +f );
  }
}

Output:

Comparing using compareTo Obj1 and Obj2: 0
Comparing using compareTo Obj1 and Obj3: -1
Comparing using equals Obj1 and Obj2: true
Comparing using equals Obj1 and Obj3: false
Comparing using compare f1 and f2: -1
Comparing using compare f1 and f3: 0
Addition of intObj1 and f1: 25+2.25=27.25

Summary

Wrapper classes are useful to convert the primitive data types into the objects and vice versa. Coming to the end of this article, we learned the importance of wrapper classes in Java. We covered the concepts of Autoboxing and Unboxing in Java with examples. We also studied various methods present in Java Wrapper classes and also implemented some methods. This article will surely help you to understand the detailed concept behind wrapper classes in Java.

Thank you for reading our article. Do share your feedback through the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.