Wrapper classes in Java are used to convert primitive data types into objects and vice versa. They allow the use of primitive data types (such as int, char, etc.) to be used as objects. This is useful because in Java, many methods and functions expect objects as arguments and not primitive data types. By using wrapper classes, we can use primitive data types as objects and pass them to these methods and functions.
There are eight wrapper classes in Java: Boolean, Byte, Character, Double, Float, Integer, Long, and Short. These classes are located in the java.lang package, which is imported by default in all Java programs.
Here are some examples of how wrapper classes can be used:
- Converting a primitive data type into an object:
int num = 10; Integer numObj = new Integer(num); // numObj is now an object that contains the value of num
- Converting an object back into a primitive data type:
Integer numObj = new Integer(20); int num = numObj.intValue(); // num is now 20
- Using a primitive data type as an object:
int num = 30; Integer numObj = num; // numObj is now an object that contains the value of num
Wrapper classes are also useful for certain collection classes (such as ArrayList) which can only store objects and not primitive data types.
Overall, wrapper classes provide a way to use primitive data types as objects, which can be useful in certain situations where objects are expected instead of primitive data types.