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