Wrapper Class in Java with Examples
Wrapper classes in Java provide a way to represent the value of primitive data types as an object. By creating an object of the wrapper class, a field is created and in this field we can store primitive data types.
Primitive Data Types
Primitive Data Types act as the basic building blocks of data manipulation in Java. They are in-built or predefined in Java. The eight Primitive Data Types include byte, short, int, long, float, double, boolean and char. This is predefined by the language.
Introduction to Wrapper Classes in Java
We have discussed about the Primitive Data Types in earlier section. Since the Primitive Data Types cannot be directly used as objects that's why Wrapper classes come into picture.
Generic classes work with objects and don't support Primitives. As a result, Wrapper classes are needed as they convert primitive data types into objects. So, let's discuss what is a wrapper class in Java in detail?
The Java programming language provides the java.lang package which has classes that are fundamental to the design and the most important classes among them are Object and Class.
So, Java wrapper classes wraps or represents the values of primitive data types as an object. When an object is created using a wrapper class, it contains a field which can store the primitive data types.
The object of one type contains a field of that particular type only, which means a Double type of object contains double type of field only.
Below are the Primitive Data Types and their corresponding Wrapper classes:
|Primitive Data Type||Wrapper Class|
Why Do We Meed Wrapper Classes in Java?
- Whenever the primitive types are required as an object, wrapper classes can be used. Wrapper classes also include methods to unwrap the object and give back the data type.
- In java.util package, the classes handle only objects. In this case wrapper class are helpful as they convert primitive data type to objects.
- In the Collection framework, Data Structures such as ArrayList store data only as objects and not the primitive types.
- Wrapper classes have methods that support object creation from other object types such as string.
- Wrapper classes are also used for synchronization in multithreading. As in synchronization process, we try to achieve that the shared resource will be used by only one thread at a time. Objects are needed for this.
Process Flow of the Wrapper Class in Java
In Java Wrapper Classes, the object is created with fields or properties in which the primitive data types can be stored.
Creating Wrapper Objects
- Using a Wrapper Class Constructor
We can create a wrapper object using the wrapper class and its constructor by passing a value to it.
However, this way of creating an instance of wrapper classes using constructor is deprecated as of the latest version of JDK. This is because each time new memory is allocated in the heap when we create an object with the help of the constructor. Also, the constructor for Character(char) has been deprecated since JDK version 9.
- Using Wrapper class only (instead of the primitive type)
We can create objects without using constructor as well by using the wrapper class instead of the primitive type to create a wrapper object without passing the value to the constructor like we did earlier method. And to get the value, we can print the particular object.
Another example where we are converting an Integer to a String, and using the length() method to calculate the length of the "string":
- Using valueOf Static methods
By using valueOf Static method, a Wrapper object can be created.
The difference in using the other methods and valueOf() static method is - By using the Constructor or Wrapper Class method we will always create a new object which will allocate a new memory in the heap each time, while using valueOf() static method, it may return a cached value with-in a range.
Features of Java Wrapper Classes
Value modification in function:
We have the 'call by value' function in Java programming, using this we can modify the arguments passed into a method with the help of the objects converted from primitive data types. In many scenarios the argument is not constant it needs to be modified then we can pass the objects and can modify the values accordingly.
To support Java synchronization an object is needed. It operates into objects in multi-threading. As for the identification of the blocks in multi-threading, objects are required.
Synchronized blocks in Java are marked with the Synchronized keyword. This block in Java is synchronized on some object. All blocks that are synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.
To implement the serialisation, the object is converted within streams. The object can be regerated using the java wrapper classes. Basically, object is must as the Serializable interface must be implemented by the class whose object needs to be persisted.
The implementaton of the utility classes in the java.util package is to match with the objects and wrapper classes help to achieve the same as well.
Java collection framework classes such as ArrayList, HashSet, Vector, LinkedList, etc. store only objects i.e. reference types and not primitive types. So objects are instances of wrapper classes and that's why it helps for this.
Methods Supported by the Wrapper Classes
All of the numeric wrapper classes are subclasses of the abstract class Number such as Byte, Integer, Double, Short, Float, Long.
Some of the frequently used methods that all subclasses of the Number class implements are listed in the following table:
|S. No.||Method||Method Description|
|1||typeValue()||Converts the value of this Number object to the specified primitive data type returned|
|2||compareTo()||Compares this Number object to the argument|
|3||equals()||Determines whether this Number object is equal to the argument|
|4||valueOf()||Returns an Integer object holding the value of the specified primitive data type value|
|5||toString()||Returns a String object representing the value of specified Integer type argument|
|6||parseInt()||Returns an Integer type value of a specified String representation|
|7||decode()||Decodes a String into an integer|
|8||min()||Returns the smaller value after comparison of the two arguments|
|9||max()||Returns the larger value after comparison of the two arguments|
|10||round()||Returns the closest round off long or int value as per the method return type|
There are more such methods which are implemented by the subclasses of the Number class. The above table lists only few of them.
Autoboxing is when the Java compiler performs the automatic conversion of the primitive data types to the object of their corresponding wrapper classes. For example, converting an int to Integer, a double to Double, etc.
The Java compiler applies autoboxing when a primitive value is:
- Passed as a parameter to a method that expects an object of the corresponding wrapper class.
- Assigned to a variable of the corresponding wrapper class.
Here, the output is 50 for all as- The 'a' variable is assigned with int value 50. The 'first' variable is assigned with the value of 'a' that is 50 only that's how int converts into Integer explicitly.
The 'second' variable will also have the value of 'a' that is 50 as due to autoboxing the compiler internally do the conversion automatically.
It is just the opposite process of autoboxing. Unboxing is automatically converting an object of a wrapper type (Integer, for example) to its corresponding primitive (int) value.
The Java compiler applies unboxing when an object of a wrapper class is:
- Passed as a parameter to a method that expects a value of the corresponding primitive type.
- Assigned to a variable of the corresponding primitive type.
Here, the output for all is 5 as-
The object 'a' is created with Integer passing the value 5. So value of 'a' is 5.
The 'first' variable is assigned with a.intValue(). The value of 'a' is 5 so value of 'first' will be 5.
The 'second' variable is assigned directly with 'a'. Due to unboxing. the compiler internally assigns the intValue of 'a' that is 5.
Wrapper Class in Java Example
You might have gained an understanding of what a wrapper class is in Java. Now, let's discuss examples that cover the usage of wrapper classes in Java.
1. Primitive Types to Wrapper Objects
In the above example, we have used the valueOf() method to convert the primitive types into objects.
Here, we have used the instanceof operator to check whether the generated objects are of Integer or Double type or not.
However, the Java compiler can directly convert the primitive types into corresponding objects. For example,
This process is known as auto-boxing which we have already discussed. In which the conversion happens for primitive types into objects internally. Like here in the above example, the primitive type value of 'a' is converted into object 'aObj'. Internally, the 'Integer.valueOf(a)' is used by the compiler and 'aObj' is assigned with the value of a that is 5.
2. Wrapper Objects into Primitive Types
In the above example, we have used the intValue() and doubleValue() method to convert the Integer and Double objects into corresponding primitive types.
However, the Java compiler can automatically convert objects into corresponding primitive types. For example,
This process is known as unboxing which we have already discussed.
Custom Wrapper Class in Java.
As the Java Wrapper classes wrap the primitive data types. Likewise, we can also create custom wrapper class in Java which wraps a primitive data type.
Here, we have created a custom wrapper class that is SpeedWrapperClass() and to set the value of speed we have also created constructors. Now, when we created an instance of the custom wrapper class and passed the integer value it worked as Integer wrapper class which wraps the int value of 100 and set the speed as 100.
Advantages and Disadvantages of Wrapper Class in Java
- In Java, sometimes we might need to use objects instead of primitive data types. For example, while working with collections. As we can see in the below example we need to use Integer not the primitive int. The primitive only specifies the range and type of the value like here it is int and the wrapper class wraps that value into an object of the specified type which is here Integer type.
- We can use the objects of the wrapper class in Java and store them as a null value. In real time scenario applications, the values can be null and hence, we need to store null values.
Objects like Character and Integer are pointers: the actual number stored in the bytes that are that variable's value represents an address in memory. Basically, these are the references to the memory address. So, it is possible and meaningful to set that number to an address that goes nowhere, which is what null is.
A primitive like int or char, however, has a number that is interpreted as a number (integer, or ASCII code), and there's no way to make it "not a number" because all that the memory can possibly store is numbers.
- A wrapper type allows a primitive to operate in more advanced ways. An integer can use it in different ways, like a class described as Hours, for example, which presents the number meaning wherever it is used.
- The primitive types just operate with value, the wrapper class provides it with a name. For example, int as Integer, char as Character, etc. It means that int only specifies the range and type of the value but by creating the object with wrapper class Integer it will be given a reference name(object).
Sure! Here are the FAQs along with their concise answers:
Which are the wrapper classes in Java? Java provides wrapper classes for each primitive data type. The wrapper classes are:
What is a wrapper class in Java with an example? A wrapper class in Java is used to represent a primitive data type as an object. For example, the Integer wrapper class can be used to represent and perform operations on integer values.
Why use a wrapper class in Java? Wrapper classes provide additional functionality and features that are not available with primitive data types. They allow us to treat primitive values as objects and provide methods for conversions, comparisons, and other operations. Wrapper classes are also useful in Java collections and when working with APIs that require objects.
What is wrapper class? Can you provide an example? A wrapper class in Java is a class that wraps or encapsulates a primitive data type, allowing it to be treated as an object. One example is the Integer wrapper class, which wraps the int primitive type.
- Wrapper classes in Java wraps the primitive data type in its class object.
- Java wrapper classes are provided in the java.lang package.
- Autoboxing and unboxing converts the primitive into objects and objects into primitives automatically.
- We can also create custom Wrapper class in Java which wraps a primitive data type.