JAVA
wrapper class in java
seoca
2019. 1. 7. 15:40
wrapper class
the primitive data type is not an object, so If we need a method that only takes objects as a parameter, it can't be used. Therefore, wrapper classes are used to convert data type into an object.
Primitive Data Type |
Wrapper instance |
char |
Character |
byte |
Byte |
short |
Short |
long |
Integer |
float |
Float |
double |
Double |
boolean |
Boolean |
Boxing & UnBoxing
The conversion of primitive data types into wrapper class is boxing. Whereas, converting an object into corresponding primitive data type is unboxing
Example code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class BoxingUnBoxing { public static void main(String[] args) { Integer iValue = new Integer(10); Double dValue = new Double(3.14); System.out.println(iValue); //10 System.out.println(dValue); //3.14 iValue = new Integer(iValue.intValue()+10); dValue = new Double(dValue.doubleValue()+1.2); System.out.println(iValue); //20 System.out.println(dValue); //4.34 } } | cs |
AutoBoxing & AutoUnBoxing
Example code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class AutoBoxingUnBoxing { public static void main(String[] args) { Integer iValue = 10; //auto boxing Double dValue = 3.14; // aut boxing System.out.println(iValue); //10 System.out.println(dValue); //3.14 int num1 = iValue; //auto unboxing double num2 = dValue; //auto unboxing System.out.println(num1); //10 System.out.println(num2); //3.14 } } | cs |