Wrapper class
- The wrapper class in Java provides the mechanism 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 |
Autoboxing: The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Unboxing: The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of autoboxing.
Example of Autoboxing & Unboxing
public class WrapperClass {
public static void main(String[] args) {
//Converting int into Integer (autoboxing)
int i = 10;
Integer x = Integer.valueOf(i); //converting int into Integer explicitly
Integer y = i; //autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(i+" "+x+" "+y);
//Converting Integer to int (unboxing)
Integer q = new Integer(20);
int z = q.intValue(); //converting Integer to int explicitly
int a = q; //unboxing, now compiler will write a.intValue() internally
System.out.println(q+" "+z+" "+a);
}
}
Conversion between String and Primitive Data type
public class StringPrimitive {
public static void main(String[] args) {
//Converting primitive to string
int i = 234;
String s = Integer.toString(i);
System.out.println("S = "+s);
//Converting String to primitive
String st = "343";
int in = Integer.parseInt(st);
//int in = Integer.valueOf(st);
System.out.println("IN = "+in);
}
}
public class StringPrimitive {
public static void main(String[] args) {
//Converting primitive to string
int i = 234;
String s = Integer.toString(i);
System.out.println("S = "+s);
//Converting String to primitive
String st = "343";
int in = Integer.parseInt(st);
//int in = Integer.valueOf(st);
System.out.println("IN = "+in);
}
}
Comments
Post a Comment