Convert Primitive Type to Object in Java

Exercise:

Write a Java Program to convert primitive type to object.

Click Here to View the Solution!
public class PrimToWrapp {
  public static void main(String[] args) {
    int var1 = 9;
    double var2 = 2.156;
    boolean var3 = false

    //converts into wrapper objects
    Integer obj1 = Integer.valueOf(var1);
    Double obj2 = Double.valueOf(var2);
    Boolean obj3 = Boolean.valueOf(var3);

    //checks if objs are objects of corresponding wrapper class  
    if(obj1 instanceof Integer) {
      System.out.println("An object of Integer Class is created.");
    }
    if(obj2 instanceof Double) {
      System.out.println("An object of Double Class is created.");
    }
    if(obj3 instanceof Boolean) {
      System.out.println("An object of Boolean Class is created");
    }
  }
} 
Click Here to View the Output!
An object of Integer Class is created.
An object of Double Class is created.
An object of Boolean Class is created
Click Here to View the Explanation!
  • In this program, first a variety of primitive type variables (int, double, and boolean) have been initialized.
  • Then these primitive type variables are converted to instances of  Java wrapper classes (int, double, and boolean) using the method valueOf().

%d bloggers like this: