Java : Wrapper Class
The purpose of using Wrapper class instead of primitive types are
- Primitive types do not use new an object to create variables and have their own values.
- Because some Java APIs can only use objects (for example, Collection), not primitive types (ie, int, long, char, boolean, etc.) to handle the data.
ArrayList
,HashMap
, etc.can only be stored in objects
- In order to make these primitive types applicable to these APIs, Java use wrapper class to do it.
Process of Auto-boxing and unboxing
Integer obj = new Integer(123);
int num = obj.intValue();
Some examples
//autobox : Primitive to Wrapper Class
int num = 7;
Integer num1 = num;
// autounbox : Wrapper Class to Primitive
int num2 = num1;
// use class method to convert string to number
String str = "150";
int num3 = Integer.parseInt(str);
System.out.println(num3 * 12);
//1800
// Convert an Integer object to an int value
Integer i = 6;
int j = i.intValue();
System.out.println(j);
// 6