Java provides classes that correspond to each of the simple types. In essence, these classes
encapsulate, or wrap, the simple types within a class. Thus, they are commonly referred to as
wrapper classes.
Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive. Autoboxing and unboxing feature facilitates the process of generates a code implicitly
to convert primitive type to the corresponding wrapper class type and vice-versa.
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:
![]() |
Wrapper class in java |
Wrapper class Example: Primitive to Wrapper
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
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 class Example: Wrapper to Primitive
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
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:
3 3 3
Comments
Post a Comment