Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Java programming, a wrapper class is a fundamental concept that provides a way to convert primitive data types into objects (reference types). Each primitive data type in Java has a corresponding wrapper class, which encapsulates its value and provides several utility methods. This conversion is essential when working with data structures that require objects rather than primitives, such as collections like ArrayLists or when using Java generics.
Wrapper classes in Java are a set of classes that allow primitive data types to be treated as objects. In Java, primitive data types like int, float, double, char, etc., are not objects. They are basic data types that store single values directly in memory. However, there are situations where these primitives need to be used as objects. Wrapper classes provide a mechanism to wrap primitive data types into objects so that they can be included in activities that require objects rather than primitives, such as collections (like ArrayLists), generics, and other object-oriented features.
Need of Wrapper Classes
Wrapper classes in Java serve several important purposes that enhance the language's flexibility and functionality:
Object Representation: Primitive data types like int, float, double, etc., are not objects and cannot be used where objects are required, such as in collections (like ArrayLists) or with Java generics. Wrapper classes provide a way to convert these primitives into objects, allowing them to be used in object-oriented contexts.
Null Values: Wrapper classes can hold null values, which primitives cannot. This is particularly useful in scenarios where the absence of a value needs to be represented.
Generics Support: Java generics require objects as type parameters. Wrapper classes enable the use of primitives in generic classes and methods by providing object representations of primitive types.
Utility Methods: Each wrapper class provides methods to perform various operations on the data it wraps. For example, the Integer class has methods for converting integers to strings, parsing strings into integers, and performing arithmetic operations.
Standardization and Interoperability: Wrapper classes facilitate standardization across Java's type system. They allow primitives to be treated uniformly with other objects, promoting consistency and interoperability within Java applications.
Type Conversion: Wrapper classes simplify type conversion between primitives and their corresponding objects. This is essential for tasks like data manipulation and integration with APIs that require object-based data handling.
Primitive Data Types and their Corresponding Wrapper Class
Primitive Type
Wrapper Class
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
char
Character
boolean
Boolean
Autoboxing
When primitive values are converted into respective wrapper class objects, this procedure is called Autoboxing.
For Example: char to Character, int to Integer, long to Long, double to Double, etc.
Let’s understand autoboxing with a sample of code:
Implementation
Java
Java
public class AutoboxingEg { public static void main(String[] args) { // Autoboxing int to Integer. int tmp = 15; Integer ntmp = tmp; System.out.println("Integer: " + ntmp);
// Autoboxing char to Character. char ch = 'p'; Character nch = ch; System.out.println("Character: " + nch); } }
You can also try this code with Online Java Compiler
Unboxing is the reverse process of Autoboxing, i.e., when an object of the wrapper class is converted to its respective primitive value, the procedure is known as Unboxing.
For Example: Boolean to boolean, Float to float, Integer to integer, etc.
The below program depicts the use of unboxing.
Implementation
Java
Java
import Java.util.ArrayList; public class UnboxingEg { public static void main(String[] args) { //Unboxing Integer into int. Integer tmp = 205; int ntmp = d; System.out.println("int: " + ntmp);
//Unboxing Double into double. Double c = 27.8; double nc = c; System.out.println("double: " + nc); } }
You can also try this code with Online Java Compiler
When we need to modify the arguments passed in to a method, we can do it by passing them in the form of wrapper class objects.
Java.util package‘s classes only deal with objects, so Wrapper class is required.
In multithreading also, an object is needed to support synchronization, so again we need to convert primitive values into objects.
In primitive data structures, we can’t store null values, whereas, in the Wrapper class objects, we can store null values.
In collection classes like LinkedList, ArrayList, etc., which store only objects and not primitive values, a wrapper class is used.
Requirements like when we want to convert one primitive data type to another primitive data type, we can do it with the help of wrapper class. For example, if we want to create an integer value from some string, we can perform it with the help of wrapper class utility “.valueOf()”.
Wrapper class methods
Method
Description
Integer valueOf(int i)
Returns the Integer object of the specified int primitive value.
String toString()
Returns a string representation of the specified value.
byte ByteValue()
short ShortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
Returns the value of this Number object into its corresponding primitive type
int compareTo(Byte byte)
int compareTo(Double double)
int compareTo(Float float)
int compareTo(Long long)
int compareTo(Integer int)
int compareTo(Short short)
Compares this Number object with the specified argument
Demonstration of Wrapper Class methods
Implementation
Java
Java
// Program to show Wrapper class methods. import Java.io.*;
// Main Class public class wrapperClass {
// Main driver method public static void main(String[] args) { // Conversion of int to Integer with the help of valueOf() utility. Integer val = Integer.valueOf(30); System.out.println(val.intValue());
// Conversion of float to Float with the help of valueOf() utility. Float fVal = Float.valueOf(6.78f); System.out.println(fVal.floatValue());
// Conversion of the binary number to an integer value. Integer bin2int = Integer.valueOf("1000", 2); System.out.println(bin2int); } }
You can also try this code with Online Java Compiler
In addition to the standard wrapper classes provided by Java (Integer, Double, etc.), developers can create custom wrapper classes tailored to specific application needs. These custom wrapper classes encapsulate primitive data types or other objects, providing additional functionality or domain-specific behavior.
Custom wrapper classes typically include:
Constructors to initialize the wrapped data.
Accessor methods to retrieve the wrapped data.
Mutator methods to modify the wrapped data.
Additional methods to perform specific operations or validations.
For example, a custom Temperature wrapper class could encapsulate a double value representing temperature, along with methods to convert between Celsius and Fahrenheit, validate temperature ranges, and provide formatted output.
Frequently Asked Questions
What is a wrapper used for?
A wrapper class in Java is used to convert primitive data types into objects. It allows primitives like int, float, etc., to be treated as objects, enabling them to be used in collections, generics, and scenarios requiring object-oriented features.
Why is boxing and unboxing used?
Boxing is the process of converting a primitive data type into its corresponding wrapper class object (e.g., int to Integer). Unboxing is the reverse process, converting a wrapper class object back to its primitive data type. This is necessary for operations that require objects, such as collections and generics, where primitives are not accepted.
Why is boxing and unboxing used?
Boxing and unboxing in Java simplify the handling of primitive data types in object-oriented contexts. Boxing converts primitives to objects (e.g., int to Integer), facilitating their use in collections and generics. Unboxing reverses this process, retrieving primitive values from wrapper objects.
Conclusion
In this article, we have discussed Wrapper classes in Java. Wrapper classes in Java play a crucial role in bridging the gap between primitive data types and objects, enhancing the language's versatility and functionality. They enable primitives to be used in object-oriented contexts like collections and generics, provide utility methods for data manipulation, and support null values.