Google News
logo
Java Program to convert primitive types to objects and vice versa
Java provides two approaches for converting primitive types to objects and vice versa:

* Boxing and Unboxing
* Using Wrapper Classes

Here are examples of both approaches:

1. Boxing and Unboxing :

Boxing is the process of converting a primitive type to its corresponding object type, while unboxing is the opposite process of converting an object type to its corresponding primitive type.
Program :
//Boxing
int num1 = 10;
Integer obj1 = Integer.valueOf(num1);

//Unboxing
Integer obj2 = new Integer(20);
int num2 = obj2.intValue();

2. Using Wrapper Classes :

Java provides wrapper classes for each of the primitive types, which can be used to convert primitive types to objects and vice versa. The wrapper class for int is Integer, for double is Double, for boolean is Boolean, and so on.
Program :
//Converting int to Integer
int num1 = 10;
Integer obj1 = new Integer(num1);

//Converting Integer to int
Integer obj2 = new Integer(20);
int num2 = obj2.intValue();
Similarly, we can use the wrapper classes for other primitive types as well.