Java Program to convert primitive types to objects and vice versa

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java Program to Convert Primitive Types to Wrapper Objects

class Main {
  public static void main(String[] args) {

    // create primitive types
    int var1 = 5;
    double var2 = 5.65;
    boolean var3 = true;

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

    // checks if obj are objects of
    // corresponding wrapper class
    if(obj1 instanceof Integer) {
      System.out.println("An object of Integer is created.");
    }

    if(obj2 instanceof Double) {
      System.out.println("An object of Double is created.");
    }

    if(obj3 instanceof Boolean) {
      System.out.println("An object of Boolean is created");
    }
  }
}

Output

An object of Integer is created.
An object of Double is created.
An object of Boolean is created.

In the above example, we have created variables of primitive types (int, double, and boolean). Here, we have used the valueOf() method of the Wrapper class (Integer, Double, and Boolean) to convert the primitive types to the objects.

To learn about wrapper classes in Java, visit Java Wrapper Class.


Example 2: Java Program to Convert Wrapper Objects to Primitive Types

class Main {
  public static void main(String[] args) {

    // creates objects of wrapper class
    Integer obj1 = Integer.valueOf(23);
    Double obj2 = Double.valueOf(5.55);
    Boolean obj3 = Boolean.valueOf(true);

    // converts into primitive types
    int var1 = obj1.intValue();
    double var2 = obj2.doubleValue();
    boolean var3 = obj3.booleanValue();

    // print the primitive values
    System.out.println("The value of int variable: " + var1);
    System.out.println("The value of double variable: " + var2);
    System.out.println("The value of boolean variable: " + var3);
  }
}

Output

The value of int variable: 23
The value of double variable: 5.55
The value of boolean variable: true

In the above example, we have created objects of Wrapper class (Integer, Double, and Boolean).

We then change the objects into corresponding primitive types (int, double, and boolean) using the intValue(), doubleValue(), and booleanValue() methods respectively.

Note: The Java compiler automatically converts the primitive types into corresponding objects and vice versa. This process is known as autoboxing and unboxing. To learn more, visit Java autoboxing and unboxing.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges