Define Wrapper Classes in Java.
In Java, wrapper classes are classes that provide a wrapper around a primitive data type. Wrapper classes are used to convert primitive data types to object types and vice versa.
Java has eight wrapper classes: Boolean
, Byte
, Character
, Double
, Float
, Integer
, Long
, and Short
. These wrapper classes correspond to the eight primitive data types in Java: boolean
, byte
, char
, double
, float
, int
, long
, and short
, respectively.
Here are some examples of how to use wrapper classes in Java:
// convert a primitive int to an Integer object int i = 10; Integer iWrapper = new Integer(i); // convert an Integer object to a primitive int int i2 = iWrapper.intValue(); // convert a primitive double to a Double object double d = 3.14; Double dWrapper = new Double(d); // convert a Double object to a primitive double double d2 = dWrapper.doubleValue();
In these examples, the Integer
and Double
wrapper classes are used to convert primitive data types (int
and double
) to object types (Integer
and Double
) and vice versa.
Wrapper classes are often used in collections that can only store objects (such as ArrayList
or HashMap
) and in situations where an object is required (such as when using method overloading).
I hope this helps! Let me know if you have any other questions.
Comments
Post a Comment