Everything in Java is an object. To make this statement true, Java introduces wrapper classes for each of its primitive data types. Wrapper classes are used to convert the primitive data type into an object.
Autoboxing is a feature of Java that automatically converts primitive data type into an object of the corresponding wrapper class. Unboxing is just opposite of autoboxing. This feature converts wrapper class object into the corresponding primitive data type.
Java provides eight wrapper classes. All the wrapper classes accept Boolean, and Character are subclasses of Number class, whereas Boolean and Character directly extend the Object class.
Primitive Data Type | Wrapper Class |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
There are three ways by which we can achieve this-
Note- You can even pass String as an argument to any wrapper class constructor except Character. The Character class constructor only takes char as an argument.
public class PrimitiveToWrapper { public static void main(String args[]) { int i = 45; Integer j = i; // this is autoboxing Integer k = new Integer(i); // calling constructor Integer l = Integer.valueOf(i); // convert int to Integer System.out.println("j = "+j); System.out.println("k = "+k); System.out.println("l = "+l); } }
Output
j = 50 k = 50 l = 50
The primitive value stored in wrapper class object can be retrieved using a method of the format primitiveValue() where primitive points the name of primitive data type.
Method | Wrapper Class in which it is present |
---|---|
booleanValue() | Boolean |
char charValue() | Character |
byteValue() | Byte, Short, Integer, Long, Float, Double |
shortValue() | Byte, Short, Integer, Long, Float, Double |
intValue() | Byte, Short, Integer, Long, Float, Double |
longValue() | Byte, Short, Integer, Long, Float, Double |
floatValue() | Byte, Short, Integer, Long, Float, Double |
doubleValue() | Byte, Short, Integer, Long, Float, Double |
public class WrapperToPrimitive { public static void main(String args[]) { Integer i = new Integer(50); //converting int to Integer int j = i.intValue(); //obtaining int from Integer int k = i; //this is unboxing System.out.println("i = "+i); System.out.println("j = "+j); System.out.println("k = "+k); } }
Output
i = 50 j = 50 k = 50