Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 18, 2020 05:20 pm GMT

Java: Wrapper Class

what is a wrapper class in Java?

A Wrapper class is a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object.

Why do we need a Wrapper class?

  1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).

  2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.

  3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.

  4. An object is needed to support synchronization in multithreading.

How to create a wrapper class for primitive data types?

// primitive data type - Wrapper Class   char                - Character   byte                - Byte   short               - Short   int                 - Integer   long                - Long   float               - Float   double              - Double   boolean             - Boolean

How to create a Wrapper class?

Let us see an example of how to create a wrapper class below.

class autoBoxing{  public static void main(String[] args){    char ch = 'a';    //converting primitive data type into an object (autoboxing)    Character a = ch;  }}

The above process is also called as Autoboxing.

Autoboxing:

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

...To be continued.

keep learning, Keep coding.


Original Link: https://dev.to/rakshakannu/java-wrapper-class-4nof

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To