[Topic->Wrapper classes in Java] www.wayofcoding.
com [Page-1]
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.
The automatic conversion of primitive into an object is known as autoboxing and vice-versa
unboxing.
There are eight wrapper class corresponding to the primitive types-
Primitive Type Wrapper class(package -> java.lang)
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Java Program
package com.woc.wrapper;
public class WrapperAutoboxingAndUnboxingTest {
public static void main(String args[]){
//converting primitive to Object
int num = 10;
Integer x = Integer.valueOf(num);//converting int into Integer explicitly
Integer y = num;//autoboxing, now compiler will write Integer.valueOf(a) internally
//Converting Object to primitive
Integer a = new Integer(20);
int i = a.intValue();//converting Integer to int explicitly
int j = a;//unboxing, now compiler will write a.intValue() internally
}
}
Note that Integer.valueOf(num) likely to yield significantly better space and time performance by caching frequently
requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other
values outside of this range, hence it is preferable over new Integer(num) which gives always a new instance.