What Is the Use of Wrapper Class in Java?

Introduction 

The most crucial foundation of every programming language is its data types, and it is the most vital element to learn for every beginner. The data type represents the type, character, and set of actions for the value that it stores. Java data types are useful in all aspects, whether creating a small program or building any application or software. 

In Java, data types are classified into two types: primitive and non-primitive data types. Primitive data types are pre-specified, whereas non-primitives are defined by programmers rather than by Java. To provide some additional functionality and make the application programs uncomplicated, the concept of the Wrapper class got introduced in Java.  

Let us understand in more detail the Wrapper class in Java. 

What Are Wrapper Classes?  

Wrapper classes are predefined classes that convert received string numeric values into primitive data types and vice versa. They are used in Java. The jre/lib/rt.jar file contains a wrapper class by default and is part of the Java library. When constructing an object for a wrapper class in Java, it has a field in which we can put primitive data types. 

Program to Understand Wrapper Classes: 

Let’s understand Java wrapper classes via this program: 

  • public class wrapdemo1 
  • { 
  •  public static void main (String[]args) 
  •  { 
  •  String i = “12”; 
  •  int j = Integer.parseInt (i); 
  •  double k = Double.parseDouble (“12”); 
  •  System.out.println (j); 
  •  System.out.println (k); 
  •  boolean status = Boolean.parseBoolean (“22”); 
  •  System.out.println (stat); 

Output: 

12 

12.0 

false 

Note that the Wrapper class only supports string numeric values, and the Boolean wrapper class is added in Java 1.5. 

The following are some wrapper classes in Java that are equivalent to basic data types: 

Primitive Data Type  Wrapper Class  Constructor Argument 
boolean  Boolean  Boolean or String 
byte  Byte  Byte or String 
char  Char  char 
int  Int  Int or String 
float  Float  Float, double, or String 
double  Double  Double or String 
long  Long  Long or String 
short  Short  Short or String 

 

Features of Java Wrapper Classes 

Some key functions of Java wrapper classes are mentioned below: 

Value Modification in Function 

The “call by value” function in Java programming enables us to modify the arguments passed into a method by using objects modified from primitive data types. We can transmit the objects and modify the values if the parameter is not constant and needs to be modified. 

Synchronization 

An object is required to allow Java synchronization. It uses multi-threading to act on objects, and objects are necessary to recognize blocks in multi-threading. 

The synchronized keyword in Java is used to identify synchronized blocks. An object is synchronized with this Java block. The same object’s synchronized blocks can only have one stream active at once. Until the stream inside the block leaves, all other processes that want to enter it are halted. 

Serialization 

The object is transformed inside streams to execute serialization. The wrapper classes in Java are used to regenerate the object. The object’s class must directly or indirectly implement the Serializable interface. 

Java.util package 

The wrapper classes for the Java.util package support the utility classes, which are made to work with objects. 

Collection Framework 

ArrayList, Vector, HashSet, LinkedList, and other Framework collection classes in Java store only objects. These objects are helpful since they are instances of wrapper classes. 

Methods Supported by the Wrapper Classes in Java 

Listed below are the methods supported by the wrapper classes in Java: 

Method  Method Description 
TypeValue()  Changes the value of a Numeric object such as Int, Float, or Double to the specific primitive data type and gives the value 
CompareTo()  The number object is compared to the argument passed 
Equals ()  Checks to see wheather this number object is equivalent to the argument 
ValueOf()  The value of the given data type is returned as an Integer object 
toString()  Gives a String object showing the value of a given Integer type argument 
parseInt()  Returns an Integer type value from a String representation 
decode()  Converts a String to an integer 
min()  Gives the smaller value outputafter comparing two arguments 
max()  Gives the bigger value output after comparing two arguments 
round()  Gives the nearest round-off value according to the method return type 

Why Do We Need Wrapper Classes in Java?  

  • When using primitive types as objects, wrapper classes in Java can be used. Furthermore, wrapper classes have methods for unwrapping the object and returning the data type. 
  • The classes only deal with objects from Java.util package. In this scenario, the wrapper class comes in handy. 
  • In the Collection framework, data structures like ArrayList only hold objects, not basic types. 
  • In Java, wrapper classes are used to support objects, such as conversions from other types. 
  • Wrapper classes are useful for multithreading synchronization. The synchronization mechanism restricts the use of a shared resource to one thread at a time. Wrapper class objects are necessary for this. 

Implementing Wrapper Class in Java  

Implementing a wrapper class is straightforward. First, create a new class that extends the desired wrapper class. For example, if you want to wrap around an InputStream, your new class would extend Java.io.InputStream. Next, add fields to your new class for any data that needs to be stored. Finally, implement the methods of the wrapper class as needed. For example, if you want your wrapper class to support reading from the underlying stream, you would need to implement the read() method of InputStream. 

Wrapper classes can be extremely helpful when you need to use a lower-level language but want to take advantage of the higher-level features of Java. By creating a wrapper class, you can avoid writing complex JNI code and still get all of the benefits of using Java. 

The two methods for implementing Wrapper Class in Java: 

  1. Autoboxing 
  2. Unboxing 
  • Autoboxing  

When the Java compiler automatically transforms primitive data types into the objects of their corresponding wrapper classes in Java, this is known as autoboxing. For instance, when changing an int to an integer, a char to char, a double to a double, and so on. 

A primitive value is autoboxed by the Java compiler when: 

  • The parameter is passed to a method that requires an object of the relevant wrapper class. 
  • Assigned to the matching wrapper class variable. 

For example: 

//Autoboxing instance of int to Integer and char to Char 

public class AutoboxSample { 

  public static void main(String args[]) { 

    char ch = ‘s’; 

    //primitive to Character conversion 

    Character s = ch; 

    int b = 100; 

    // Changing int into Integer explicitly 

    Integer fir = Integer.valueOf(b); 

    // now the compiler will compose Integer.valueOf(b)  

    // internally and hence doesn’t generate an error 

    Integer sec = b; 

    System.out.println(b); 

    System.out.println(first); 

    System.out.println(sec); 

  } 

} 

Output: 

100 

100 

100 

Explanation: 

In this case, the total output is 100 as follows: 

  • The int value 100 is allocated to the B variable. 
  • The initial variable is provided the value 100 of B. Only in this instance is the primitive data type int explicitly changed to Integer. 
  • The second one will similarly have a value of 100 since autoboxing allows the compiler to execute the conversion implicitly. 

Unboxing 

It is exactly the reverse of the autoboxing method. Unboxing is the process of reverting a wrapper class object to its corresponding primitive value. 

The compiler uses unboxing when a wrapper class is: 

  • When passed as an argument to a method that takes a primitive type value 
  • Assigned to a primitive type-corresponding variable 

For example: 

//Example of unboxing changing Integer to int and Character to char 

public class UnboxExam { 

  public static void main(String args[]) { 

    Character ch = ‘F’; 

    //Char object to primitive change 

    char F = ch; 

    Integer B = new Integer(10); 

    //Converting Integer to int explicitly 

    int fir = B.intValue(); 

    //compiler will write B.intValue() internally 

    int sec = B; 

    System.out.println(B); 

    System.out.println(fir); 

    System.out.println(sec); 

  } 

}     

Output: 

10 

10 

10 

Explanation: 

Here, the output is 10 for all the queries: 

  • Object B is constructed by providing the value 10 to an Integer. 
  • The first variable is given the value B.intValue (). Because the value of B is 10, the value of the first will also be 10. 
  • The second variable is allocated directly. Because of unboxing, the compiler allocates the integer value of B, which is 10 to second. 

Benefits of Wrapper Classes 

There are various benefits of wrapper classes. Listed below are the key ones: 

  • The wrapper class in Java includes many methods for working with collections, such as sorting and searching. 
  • We can utilize the wrapper class objects and save them as null values. 
  • A wrapper type allows a primitive to perform more complex operations. An integer can utilize it in a variety of ways, such as a class called Hours, which displays the number’s value everywhere it is used. 
  • The primitive types only work on values; the wrapper class gives them names. 
  • Wrapper objects are natural objects with null references. This allows for the use of a ‘not set’ state, which is difficult to do with primitives. 
  • Pointers are objects such as integers and characters. The variable’s value in bytes represents a memory address. They are pointers to memory addresses. As a result, that number can be assigned to an address that leads it nowhere. 
  • A primitive data type, such as char or int, includes a number that can only be processed as a number (ASCII code or integer) because memory can only hold numbers. 
  • A wrapper class enables a primitive data type to be used differently. An integer can use this data type in a wide range of ways. For example, a class ‘Hours’ will always symbolize the number wherever it is applied. 
  • The primitive types merely return the value, whereas the wrapper class returns a name. For instance, int as Integer indicates that only integer provides the type and range of the value. However, by using the wrapper class ‘Integer,’ the object is provided with a reference name. 
  • All of the numeric wrapper classes, including Int, Byte, Short, Double, Long, and Float, are subclasses of the abstract class Number. 

Conclusion 

Wrapper classes in Java are the foundation of all method invocations. It also enables Java to modify basic data types without affecting their values. Practice more and more wrapper classes in Java programs to get an understanding of wrapper classes in Java. A solid understanding of these concepts will undoubtedly help you much in your development path. For programming knowledge and more reading materials on software development, UNext is the right choice for you. 

Related Articles

loader
Please wait while your application is being created.
Request Callback