Convert Object to Primitive Type in Java

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, and Boolean variables are assigned values by using the methods: intValue(), doubleValue(), and booleanValue() of Wrapper class respectively.
  • This conversion from objects to primitive types and vice versa is done by the Java compiler automatically. This concept is referred as autoboxing and unboxing.

%d bloggers like this: