🔰 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?
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).
The classes in java.util package handles only objects and hence wrapper classes help in this case also.
Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.
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. 💖
Top comments (1)
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.