Followers

coreJava: Wrapper class

Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.
Since Java 1.5, autoboxing and unboxing feature converts primitive into object and object into primitive automatically. The automatic conversion of primitive into object is known and autoboxing and vice-versa unboxing.
One of the eight classes of java.lang package are known as wrapper class in java. The list of eight wrapper classes are given below:

Primitive Type
Wrapper class
boolean
Boolean
char
Character
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double

Primitive to Wrapper conversion
public class AutoBoxing{ 
public static void main(String args[]){ 
int a=20; 
Integer i=Integer.valueOf(a);//converting int into Integer 
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally 
 
System.out.println(a+" "+i+" "+j); 
}} 
Output:
20 20 20


Wrapper to Primitive conversion
public class UnBoxing{   
public static void main(String args[]){   
//Converting Integer to int   
Integer a=new Integer(12);   
int i=a.intValue();//converting Integer to int 
int j=a;//unboxing, now compiler will write a.intValue() internally        
System.out.println(a+" "+i+" "+j);   
}}   
Output:
12 12 12




No comments:

Post a Comment