DEV Community

Cover image for Java: Wrapper Class ⭐️
Raksha Kannusami
Raksha Kannusami

Posted on

19 8

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
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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. 💖

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
vlasales profile image
Vlastimil Pospichal

I don't use wrapper classes, because "weight" is not float or instance of Float, but instance of Weight with some other attributes, eg. unit.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay