A wrapper class in Java is a class that wraps basic data types as objects. In this blog, we will understand what is a wrapper class in Java, from its definition and usage to understanding basic data types(int, float etc.,) and their corresponding wrapper classes. You will also learn about how a wrapper class is automatically converted to its corresponding primitive data type in Java, practical examples, and creating custom wrapper classes.
Table of Contents
Kickstart your programming journey with our Java Programming Tutorial:
What is a Wrapper Class in Java?
A wrapper class in Java is a special type of class that allows the basic data types to be used as objects. It serves as a container, wrapping together two or more of these basic data types (like integers, characters, etc.) and providing additional functionality. Wrapper classes enable these simple data types to be treated as objects, allowing for the utilization of object-oriented features and methods, which are otherwise not available for basic data types in Java.
Example of a Wrapper Class in Java
Hence, we know the answer to “What is a wrapper class in Java?” Let us get a better insight into wrapper classes in Java using an example.
Java program to demonstrate Wrapping and UnWrapping in Classes
import java.io.*;
class intellipaat {
public static void main(String[] args)
{
byte x = 2;
// wrapping around Byte object
Byte byteobj = new Byte(x);
// Byte byteobj = Byte.valueOf(x);
int y = 12;
// wrapping around Integer object
Integer intobj = new Integer(y);
// Integer intobj = Integer.valueOf(b);
float z = 9.6f;
// wrapping around Float object
Float floatobj = new Float(z);
// Float floatobj = Float.valueOf(z);
// double data type
double d = 205.5;
// Wrapping around Double object
Double doubleobj = new Double(d);
// Use with Java 9
// Double doubleobj = Double.valueOf(d);
// char data type
char c = 'A';
// wrapping around Character object
Character charobj = c;
// printing the values from objects
System.out.println(
"Values of Wrapper objects (printing as objects)");
System.out.println("\nByte object: "+ byteobj);
System.out.println("\nInteger object: "+ intobj);
System.out.println("\nFloat object: "+ floatobj);
System.out.println("\nDouble object: "+ doubleobj);
System.out.println("\nCharacter object: "+ charobj);
// objects to data types (retrieving data types from objects) unwrapping objects to primitive data types
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;
// printing the values from data types
System.out.println("\nUnwrapped values (printing as data types)");
System.out.println("\nbyte value: " + bv);
System.out.println("\nint value: " + iv);
System.out.println("\nfloat value: " + fv);
System.out.println("\ndouble value: " + dv);
System.out.println("\nchar value: " + cv);
}
}
Output:
The above Java code illustrates the process of wrapping and unwrapping primitive data types using their respective wrapper classes.
1. Initialization: Primitive variables (`x`, `y`, `z`, `d`, `c`) are initialized with specific values representing different data types.
2. Wrapping: Wrapper classes (`Byte`, `Integer`, `Float`, `Double`, `Character`) are utilized to wrap the primitive values. Another name of wrapping is boxing. For example, `Byte byteobj = new Byte(x)` creates a Byte object (`byteobj`) encapsulating the primitive byte value (`x`).
3. Printing Wrapped Objects: The values of the wrapper objects are printed using a function `System.out.println()`, where the System.out object represents the standard output stream, and the println() method is a member of this object used for printing.
4. Unwrapping: Unwrapping also referred to as unboxing is the term used to refers to the process of converting an object of a wrapper class back to its corresponding primitive data type. For instance, `byte bv = byteobj;` extracts the byte value from the `Byte` object.
5. Printing Unwrapped Values: The unwrapped values are printed, demonstrating the successful conversion from wrapper objects back to their primitive data types.
Are you interested in learning Java? Enroll in our Java Online Course now!
Use of Wrapper Classes in Java
The primary use of wrapper classes lies in allowing basic data types to be treated as objects. This enables the utilization of object-oriented concepts like inheritance and polymorphism which require objects.
Wrapper classes in Java serve several essential purposes:
1. Conversion: They facilitate the conversion of basic data types into objects and vice versa. This conversion allows using primitive types in scenarios where objects are required, like in collections such as ArrayList and HashMap.
2. Null Values: They solve the problem of primitive data types not being able to show that a value is missing (null). Wrapper classes allow null to be assigned, indicating the absence of a value.
3. Utilities: Wrapper classes offer utility methods to perform various operations on the underlying data types. For instance, integer class methods help with converting strings to integers, performing arithmetic operations, etc.
4. Standardization: They provide standard constants like MIN_VALUE, MAX_VALUE, and SIZE for different data types, helping in consistent and uniform programming practices across different contexts.
Primitive Data Types and Their Corresponding Wrapper Class
These wrapper classes in Java serve as object representations for their respective primitive data types, allowing them to be used in object-oriented contexts. Here’s a table showcasing primitive data types and their corresponding wrapper classes in Java:
Primitive Type |
Wrapper Class |
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
double |
Double |
float |
Float |
char |
Character |
boolean |
Boolean |
Autoboxing and Unboxing in Java
Autoboxing and unboxing are concepts in Java that deal with the automatic conversion between primitive types and their corresponding wrapper classes. Let us understand both concepts in detail in the coming section.
Autoboxing in Java
Autoboxing in Java automatically converts primitive data types (like int, double, and boolean) into their respective wrapper classes (Integer, Double, and Boolean) without needing explicit code from the programmer. This feature simplifies the process of working with both primitive types and objects. For instance, when you assign a primitive int value to an Integer object, Java automatically handles this conversion for you.
Example:
import java.util.*;
import java.lang.*;
import java.io.*;
class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=12;
Integer i=Integer.valueOf(a);
Integer j=a;
System.out.println(a+" "+i+" "+j);
}
}
Output:
Unboxing in Java
Unboxing in Java automatically converts wrapper class objects (like Integer, Double, and Boolean) back into their corresponding primitive data types (int, double, and boolean). For example, when you assign an Integer object to an int variable, Java automatically extracts the underlying int value from the Integer object.
Example:
import java.util.*;
import java.lang.*;
import java.io.*;
class WrapperExample2{
public static void main(String args[]){
Integer a=new Integer(35);
int i=a.intValue();
int j=a;
System.out.println(a+" "+i+" "+j);
}
}
Output:
Learn Java from scratch with this free Java Tutorial!
How to Create a Custom Wrapper Class
Creating a custom wrapper class in Java involves designing a class that contains a primitive data type, similar to the built-in wrapper classes like Integer or Double. To create a custom wrapper class we follow the below steps.
Step 1: Choose the Data Type: Decide which primitive data type you want to wrap. For example, consider wrapping an int.
Step 2: Create the Class: Define a class that holds the primitive data type as its private member. Let’s call it CustomIntWrapper.
Step 3: Provide Constructors: Create constructors to initialize the object of your custom wrapper class. For instance, a constructor takes an int parameter and assigns it to the internal variable.
Step 4: Implement Methods: Add methods to perform operations or manipulations with the wrapped data. For instance, methods to get, set, or perform calculations with the wrapped int value.
Example:
// Java Program to implement
// Custom wrapper class
import java.io.*;
// wrapper class
class Maximum {
private int maxi = 0;
private int size = 0;
public void insert(int x)
{
this.size++;
if (x <= this.maxi)
return;
this.maxi = x;
}
public int top() { return this.maxi; }
public int elementNumber() { return this.size; }
};
class intellipaat {
public static void main(String[] args)
{
Maximum x = new Maximum();
x.insert(1);
x.insert(3);
x.insert(2);
System.out.println("Maximum element: " + x.top());
System.out.println("Number of elements inserted: "+ x.elementNumber());
}
}
Output:
Advantages of Wrapper Class in Java
Wrapper class in Java offers several advantages, we will discuss some of the important advantages in detail below:
- Enables the use of primitive types in generic classes and collections.
- Allows representation of null values for primitive types.
- Provides methods for easy conversion between primitive types and wrapper objects.
- Wrapper classes include constants for maximum and minimum allowable values.
Check out these Top 100 Java Interview Questions to excel in your job interview.
Disadvantages of Wrapper Class in Java
The Wrapper class in Java offers various advantages, such as enabling the use of primitive but it also comes with some disadvantages, we will discuss the disadvantages of wrapper class in Java below.
- Introduces additional memory overhead compared to primitive types.
- Operations may be less performant due to object-related overhead.
- Wrapper classes are generally immutable, limiting mutability.
- Automatic conversion can lead to performance overhead.
Conclusion
Wrapper classes in Java act as a helpful hand for basic data types, making them look and act like fancy objects. They help in doing conversions of data types, handling empty values, and providing helpful tools for working with numbers. But they also bring some problems, like taking up more space, making things a bit slower, and sometimes causing unexpected issues. It is important to use them wisely, considering their upsides and downsides.
FAQs
How do wrapper classes help with null values?
Wrapper classes allow for null values, unlike primitive types. This ability is beneficial when representing the absence of data in certain situations.
Are wrapper classes immutable?
Yes, once a wrapper object is created, its value cannot be changed. Any modifications create a new object instead of modifying the existing one.
What issues might arise with autoboxing and unboxing?
Auto-conversion between primitive types and wrapper classes can occasionally lead to unexpected behavior or performance issues if not used judiciously.
In what scenarios are wrapper classes less efficient?
Wrapper classes might be less efficient in applications with heavy memory constraints or where performance is critical, as they consume more memory and introduce additional processing overhead compared to primitives.