?– Wrapper classes are classes that allow primitive types to be accessed as objects.
Wrapper classes in Java are classes that provide a way to use primitive data types (such as int, char, float, etc.) as objects. In Java, everything is treated as an object, but primitive data types are not. Wrapper classes serve as a means to wrap primitive data types into objects.
The wrapper classes in Java are:
- Integer – for int
- Character – for char
- Boolean – for boolean
- Byte – for byte
- Short – for short
- Long – for long
- Float – for float
- Double – for double
These classes provide methods to perform various operations on the data types, convert them to and from strings, and more. For example, you can use methods like parseInt()
in the Integer class to convert a string to an integer or toString()
to convert an integer to a string.
Here’s an example of using a wrapper class:
Integer myInt = new Integer(42); // Wrapping int into Integer object
int unwrappedInt = myInt.intValue(); // Unwrapping Integer object to int
In modern Java, autoboxing and unboxing have simplified the usage of wrapper classes, allowing automatic conversion between primitive types and their corresponding wrapper classes. For example:
Integer myInt = 42; // Autoboxing (converting int to Integer)
int unwrappedInt = myInt; // Unboxing (converting Integer to int)
In summary, wrapper classes in Java are used to represent primitive data types as objects, providing additional functionalities and compatibility with the object-oriented features of Java.