about 9 years ago
Wrapper Class:
In Java there are 8 primitive data types and to convert them into object we use wrapper classes. We use boxing and autoboxing to convert primitive into object and object into primitive.
Primitive Type | Wrapper class |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
Converting Primitive to Wrapper:
public class PrimitivetoWrapper{
public static void main(String args[]){
int m=10;
Integer i=Integer.valueOf(m);//converting int into Integer
Integer j=m;//autoboxing, compiler will write Integer.valueOf(m) internally
System.out.println(m+" "+i+" "+j);
}}
public class PrimitivetoWrapper{
public static void main(String args[]){
int m=10;
Integer i=Integer.valueOf(m);//converting int into Integer
Integer j=m;//autoboxing, compiler will write Integer.valueOf(m) internally
System.out.println(m+" "+i+" "+j);
}}
In the above example we are wrapping int m into its wrapper class(Integer) and showing its value.
Converting Wrapper to Primitive:
public class WrappertoPrimitive{
public static void main(String args[]){
Integer m=new Integer(3);
int i=m.intValue();//converting Integer to int
int j=m;//unboxing, now compiler will write m.intValue() internally
System.out.println(m+" "+i+" "+j);
}}
public class WrappertoPrimitive{
public static void main(String args[]){
Integer m=new Integer(3);
int i=m.intValue();//converting Integer to int
int j=m;//unboxing, now compiler will write m.intValue() internally
System.out.println(m+" "+i+" "+j);
}}
In the above example we are unwrapping "m"(Integer) into its primitive type(int) and showing its value.
0 Comment(s)