Wrapper classes In Java

Wrapper-classes

Java Wrapper classes 

A class called a Wrapper classes is one whose object contains or wraps primitive data types. An object to a wrapper class contains a field where we can store primitive data types when it is created. In other words, a primitive value can be wrapped in a wrapper class object. To know more read the further article .

Uses Of Wrapper Classes :

  • Modify the method’s value: Java only supports call by value. Therefore, if we pass a primitive value, the original value will not be changed. But if we turn a primitive value into an object, the original value will be altered.
  • Serialization: In order to perform serialization, the objects must be transformed into streams. If we have a primitive value, we can use the wrapper classes to turn it into an object.
  • Synchronization: Java synchronization is compatible with multithreaded objects.
  • java.util package:The utility classes to work with objects are provided by the java.util package.
  • Collection Framework: Only objects are supported by the Java collection framework. The collection framework’s classes (such as ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, and ArrayDeque) all only deal with objects.

Primitive Data Types and Associated Wrapper Classes

Primitive Data type Wrapper classes
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean

Autoboxing and Unboxing

Autoboxing :  is the process of automatically converting primitive data types into their corresponding wrapper classes, such as int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.

Example code for Autoboxing

Run

public class Main{
    public static void main(String[] args) {
        Integer iOb = 100;
        Double dOb = 98.6;
        dOb = dOb + iOb;
        System.out.println("dOb after expression: " + dOb);
    }
}

Output

dOb after expression: 198.6

 

Unboxing: It simply involves autoboxing in reverse. Unboxing is the process of automatically converting a wrapper class object to its corresponding primitive type.
For example – conversion of Integer to int, Long to long, Double to double, etc.

Example code for Unboxing

Run

public class Main{
    public static void main(String[] args) {
        Integer iOb = 100;
        int i = iOb;
        System.out.println(i + " " + iOb);
    }
}

Output

100 100

 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription