Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Wrapper Class in Java

Last Updated on October 16, 2023 by Ankit Kochar

In Java, primitive data types like int, char, and float are simple and efficient for basic data storage, but they lack the flexibility to work with objects and perform certain operations. To bridge this gap between primitive types and objects, Java provides a set of wrapper classes. Wrapper classes are a group of classes that encapsulate primitive data types, allowing them to be treated as objects.
In this article, we’ll explore the concept of wrapper classes in Java. We’ll discuss why and when you should use wrapper classes, how to create instances of wrapper classes, and the various methods they provide for converting between primitive types and objects. Understanding wrapper classes is crucial for working with collections, generics, and other Java features that require objects instead of primitives.

What is a Wrapper Class in Java?

A Wrapper class in Java is a class that wraps around a primitive data type and converts it into an object. Wrapper classes provide a way to treat primitive data types, such as int or double, as objects. This allows you to use the primitive data types in places where only objects are accepted, such as in collections. The eight primitive data types (boolean, char, byte, short, int, long, float, and double) in Java are not objects, but the wrapper classes (Boolean, Character, Byte, Short, Integer, Long, Float, and Double) are.

Each Wrapper class in java has a constructor that takes a single argument of the corresponding primitive data type. For example, you can use the Integer class to convert an int value into an Integer object:

int i = 42;
Integer iWrapped = new Integer(i);

Wrapper classes also provide utility methods for converting primitive values to and from binary and hexadecimal representations:

int i = 42;
String binary = Integer.toBinaryString(i);
String hex = Integer.toHexString(i);

Another important aspect of Wrapper classes is the ability to use them in place of primitive data types in collections, such as arrays and lists. Since the primitive data types are not objects, they cannot be directly stored in collections. The Wrapper classes provide a way to store primitive values as objects:

List list = new ArrayList();
list.add(42);

The Wrapper classes also provide methods for comparing and manipulating the values they contain. For example, the Integer class provides methods for comparing two Integer objects, such as compareTo(), equals(), and compare():

Integer i1 = 42;
Integer i2 = 43;
int result = i1.compareTo(i2);

And the Character class provides methods for testing the type of characters and converting them to uppercase or lowercase:

Character c = 'a';
boolean isLowerCase = Character.isLowerCase(c);
char upperCase = Character.toUpperCase(c);

Wrapper classes also provide support for autoboxing and unboxing, which allows you to use primitive data types and Wrapper objects interchangeably. Autoboxing is the process of converting a primitive value into an object of the corresponding Wrapper class in java automatically, while unboxing is the process of converting a Wrapper object back into a primitive value. This makes it possible to use Wrapper objects and primitive values interchangeably in your code:

int i = 42;
Integer iWrapped = i; // Autoboxing
int j = iWrapped; // Unboxing

Summarising Wrapper class in java provides a way to treat primitive data types as objects in Java. They provide a set of utility methods for converting, comparing, and manipulating primitive values, and are particularly useful for working

Need of Wrapper Class in Java

Wrapper classes in Java are used to wrap primitive data types (such as int, char, and boolean) in an object. This is necessary because in Java, everything is an object, and objects are required in certain situations, such as when a method requires an object as a parameter or when you need to store multiple values in a single structure like an ArrayList or a HashMap.

Each primitive data type has a corresponding wrapper class: Integer for int, Character for char, Boolean for boolean, etc. Wrapper classes provide useful methods for converting primitive values to and from strings, comparing values, and performing other operations.

For example, the Integer class has a static method called parseInt that can be used to convert a string representation of an integer into an int value, and the toString method can be used to convert an int value into a string. This can be particularly useful when reading data from a file or user input.

Another benefit of using wrapper classes is that they provide an easy way to represent null values. When a primitive value is set to its default value (such as 0 for int or false for boolean), it is unclear whether the value was explicitly set to that default or if it has not been initialized. By using a wrapper class, you can set a reference to null, which makes it clear that the value has not been initialized.

Wrapper classes also allow you to use primitive data types in collections, such as ArrayList, where only objects can be stored. By wrapping the primitive value in an object, you can store it in the collection.

In conclusion, the wrapper classes in Java serve a crucial purpose in providing a way to represent primitive data types as objects. They offer a convenient way to perform various operations on primitive values and also provide a way to store null values and use primitive data types in collections.

In Java, the eight classes that make up the java.lang package are referred to as wrapper classes. Following is a list of the eight wrapper classes:

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

Uses of Wrapper Class in Java

The main uses of the wrapper class in Java are

  • Representing primitive data types as objects: Wrapper classes provide a way to use primitive data types as objects, which is necessary in certain situations where only objects are accepted, such as in collections like ArrayList and HashMap.
  • Storing null values: Primitive data types in Java cannot store null values, but wrapper classes can be set to null, which can be useful in representing missing or unknown values.
  • Method parameters: Wrapper classes can be used as method parameters, allowing methods to accept objects instead of primitive data types.
  • Autoboxing and unboxing: Wrapper classes provide automatic conversions between primitive data types and their corresponding wrapper objects through a feature called autoboxing and unboxing.
  • Converting between primitive data types and strings: Wrapper classes provide methods for converting primitive values to and from strings, which can be useful for reading data from a file or user input.
  • Comparing values: Wrapper classes provide methods for comparing values, such as equals() and compareTo(), which can be useful for sorting and searching.
  • Performing mathematical operations: Wrapper classes provide methods for performing mathematical operations, such as addition, subtraction, and multiplication, on primitive values.

Autoboxing in Java

Autoboxing in Java refers to the automatic conversion of primitive data types to their corresponding wrapper classes. This feature was introduced in Java 5 and makes it easier to use primitive values in situations where only objects are accepted, such as in collections and method parameters.
Prior to Java 5, converting a primitive value to its corresponding wrapper class in java required manual conversion, using the constructor of the wrapper class.

Example of Autoboxing

Here we will look at the example of autoboxing in the wrapper class in java

Code:

import java.util.*;
import java.lang.*;
import java.io.*;


 class WrapperExample1{  
public static void main(String args[]){  
//Converting int into Integer  
int a=22;  
Integer i=Integer.valueOf(a);
Integer j=a;
  
System.out.println(a+" "+i+" "+j);  
}}

Output

22 22 22

Explanation of the above example
In the above example we have converted the int which is a primitive data type into Integer using wrapper class in java.

Autoboxing is performed automatically in the following situations:

  • When assigning a primitive value to a variable of its corresponding wrapper class.
  • When passing a primitive value as an argument to a method that requires an object of the corresponding wrapper class.
  • When storing a primitive value in a collection that requires objects, such as an ArrayList or a HashMap.

Autoboxing has several benefits, including improved code readability, reduced code verbosity, and easier use of primitive values in situations where only objects are accepted.

It is important to note that autoboxing is performed only for the primitive data types and their corresponding wrapper classes defined in the java.lang package: boolean and Boolean, char and Character, byte and Byte, short and Short, int and Integer, long and Long, float and Float, and double and Double.

Unboxing in Java

In Java, wrapper classes are used to wrap primitive data types such as int, char, etc. into objects. This is useful when working with collections, where only objects can be stored, not primitive data types. The wrapper classes also provide additional methods that can be useful in processing the wrapped data. The process of converting a wrapper class in java’s object back into its corresponding primitive data type is called "unboxing."

To unbox a wrapper class object, the valueOf() method is used. The valueOf() method takes a String as a parameter and returns an object of the corresponding wrapper class.

Example of Unboxing

Unboxing is the opposite of autoboxing as here we will convert the class into a primitive data type.

Code:

import java.util.*;
import java.lang.*;
import java.io.*;

 class WrapperExample2{    
public static void main(String args[]){    
Integer a=new Integer(43);    
int i=a.intValue(); 
int j=a;   
    
System.out.println(a+" "+i+" "+j);    
}}

Output

43 43 43

Explanation of the above example
In the above example we have converted the Integer type class into int type primitive data type. By using wrapper class in java.

Example of Wrapper Class in Java

In this section, we will discuss the example of a wrapper class in java where we convert the primitive data type into corresponding class or objects.

Code:

//Java Program to convert all primitives into its corresponding   
//wrapper objects and vice-versa  
 class WrapperExample3{  
public static void main(String args[]){  
byte b=2;  
short s=42;  
int i=34;  
long l=40;  
float f=75.0F;  
double d=20.0D;  
char c='n';  
boolean b2=false;  
  
Byte byteobj=b;  
Short shortobj=s;  
Integer intobj=i;  
Long longobj=l;  
Float floatobj=f;  
Double doubleobj=d;  
Character charobj=c;  
Boolean boolobj=b2;  
  
//Printing objects  
System.out.println("---Printing object values---");  
System.out.println("Byte object: "+byteobj);  
System.out.println("Integer object: "+intobj);  
System.out.println("Short object: "+shortobj);  
System.out.println("Long object: "+longobj);  
System.out.println("Double object: "+doubleobj);  
System.out.println("Float object: "+floatobj);  
System.out.println("Boolean object: "+boolobj); 
System.out.println("Character object: "+charobj);  
 
  
//Unboxing: Converting Objects to Primitives  
byte bytevalue=byteobj;  
short shortvalue=shortobj;  
int intvalue=intobj;  
long longvalue=longobj;  
float floatvalue=floatobj;  
double doublevalue=doubleobj;  
char charvalue=charobj;  
boolean boolvalue=boolobj;  
  
//Printing primitives  
System.out.println("---Printing primitive values---");  
System.out.println("byte value: "+bytevalue);  
System.out.println("int value: "+intvalue); 
System.out.println("short value: "+shortvalue);  
System.out.println("long value: "+longvalue);  
System.out.println("double value: "+doublevalue);
System.out.println("float value: "+floatvalue); 
System.out.println("boolean value: "+boolvalue);  
System.out.println("char value: "+charvalue);  
}}

Output

---Printing object values---
Byte object: 2
Integer object: 34
Short object: 42
Long object: 40
Double object: 20.0
Float object: 75.0
Boolean object: false
Character object: n
---Printing primitive values---
byte value: 2
int value: 34
short value: 42
long value: 40
double value: 20.0
float value: 75.0
boolean value: false
char value: n

Explanation of the above example
In the above code we have taken all the eight primitive data type and have converted them into their classes or object like int to Integer and we can see the conversion in the output.

Custom Wrapper Class in Java

In Java we use a wrapper class in java to wrap the primitive data type but instead of using the wrapper class in java, we can create our own custom class which will wrap the primitive data type just like the wrapper class in java.

Example of Custom Wrapper class in Java
Now, we will look at the example of creating a custom wrapper class.

class Javatpoint{  
private int i;  
Javatpoint(){}  
Javatpoint(int i){  
this.i=i;  
}  
public int getValue(){  
return i;  
}  
public void setValue(int i){  
this.i=i;  
}  
@Override  
public String toString() {  
  return Integer.toString(i);  
}  
}  
class TestJavatpoint{  
public static void main(String[] args){  
Javatpoint j=new Javatpoint(40);  
System.out.println(j);  
}}

Output

40

Explanation of the above code
In the above example we are using the getter and setter functions to get and change the value of the private member of the class and after that, we are wrapping the value of the primitive data type just like wrapper class in java.

Advantages of Wrapper Class in Java

The following are the advantages of the wrapper class in java

  • Provide an Object representation of primitive data types: Wrapper classes provide an object representation of primitive data types, which allows developers to use primitives as objects in their code.
  • Facilitate type conversion: Wrapper classes can be used to convert primitive data types to and from String representation, making it easy to store primitives in collections or pass them as method arguments.
  • Help in implementing Autoboxing and Unboxing: Java provides a feature called Autoboxing and Unboxing, which automatically converts between primitive and wrapper class objects, simplifying the code and reducing the number of explicit type conversions required.

Disadvantages of Wrapper Class in Java

Below are the disadvantages of the wrapper class in java.

  • Performance Overhead: The process of converting primitive data types to and from Wrapper classes can result in performance overhead, especially in large-scale applications where this conversion takes place frequently.
  • Increased Memory Usage: Wrapper classes consume more memory than primitive data types, as they are objects and contain additional information like type information, methods, etc.
  • Immutable: Wrapper classes are immutable, meaning their values cannot be changed once they are created. This can be limiting in certain situations where it is necessary to modify the value of a primitive data type.

Conclusion
Wrapper classes in Java provide a bridge between primitive data types and objects, enabling developers to work with both efficiently. They offer a set of methods and utilities for converting between primitives and objects and are essential when working with collections, generics, and other parts of the Java API that require objects.

In this article, we’ve explored the concept of wrapper classes, their usage, and the most commonly used wrapper classes in Java. We’ve also discussed autoboxing and unboxing, which simplify the process of converting between primitives and their corresponding wrapper objects.

As you continue to develop Java applications, remember that wrapper classes are valuable tools for handling primitive data in object-oriented contexts. By mastering their usage, you can write more flexible and robust code that seamlessly integrates primitives and objects.

Frequently Asked Questions Related to Wrapper Class in Java

Here are some FAQs related to Wrapper Class in Java.

1. Can I convert between wrapper classes and primitive types in Java?
Yes, you can convert between wrapper classes and primitive types using methods provided by the wrapper classes. For example, you can use the intValue() method to extract the int value from an Integer object.

2. What are the common wrapper classes in Java?
The common wrapper classes in Java are Integer, Double, Character, Boolean, Float, Long, Short, and Byte. Each corresponds to a specific primitive data type.

3. What is autoboxing and unboxing in Java?
Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class object, and unboxing is the reverse process. These features were introduced in Java to simplify the conversion between primitives and objects.

4. How can I create an instance of a wrapper class in Java?
You can create an instance of a wrapper class using its constructor, such as Integer myInt = new Integer(42);. However, autoboxing allows you to create instances more conveniently, like Integer myInt = 42;.

5. When should I use wrapper classes over primitive data types?
You should use wrapper classes when working with collections, generics, or APIs that require objects. Additionally, wrapper classes are useful for representing null values for primitive data types.

Leave a Reply

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