Exercise:
Write a Java Program to convert object to primitive type.
Click Here to View the Solution!
public class WrappToPrim{
public static void main(String[] args) {
Integer obj1 = Integer.valueOf(
19);
Double obj2 = Double.valueOf(
9.17);
Boolean obj3 = Boolean.valueOf(
true);
int var1 = obj1.intValue();
double var2 = obj2.doubleValue();
boolean var3 = obj3.booleanValue();
System.out.println(
"The value of integer variable is " + var1);
System.out.println(
"The value of double variable is " + var2);
System.out.println(
"The value of boolean variable is " + var3);
}
}
Click Here to View the Output!
The value of integer variable is 19 The value of double variable is 9.17 The value of boolean variable is true
Click Here to View the Explanation!
- In this program, initially some objects of
Java wrapper classes (int, double, and boolean)
have been initialized. - These objects are then converted to their corresponding
primitive types
.Int
,double
, andBoolean
variables are assigned values by using the methods:intValue()
,doubleValue()
, andbooleanValue()
ofWrapper class
respectively. - This conversion from
objects
toprimitive
types and vice versa is done by the Java compiler automatically. This concept is referred asautoboxing
andunboxing
.