Java program to convert primitive types to objects and vice versa

Java provides wrapper classes for each primitive data type, which can be used to convert primitive types to objects and vice versa. Here's an example program that demonstrates how to convert primitive types to objects and vice versa using the wrapper classes:

refer t‮gi:o‬iftidea.com
public class WrapperExample {
    
    public static void main(String[] args) {
        
        // Convert primitive types to objects
        int i = 123;
        Integer integer = Integer.valueOf(i);
        System.out.println("Converted integer: " + integer);
        
        double d = 3.14;
        Double doubleObj = Double.valueOf(d);
        System.out.println("Converted Double: " + doubleObj);
        
        boolean b = true;
        Boolean booleanObj = Boolean.valueOf(b);
        System.out.println("Converted Boolean: " + booleanObj);
        
        // Convert objects to primitive types
        Integer integerObj = new Integer(456);
        int j = integerObj.intValue();
        System.out.println("Converted int: " + j);
        
        Double doubleObj2 = new Double(1.23);
        double x = doubleObj2.doubleValue();
        System.out.println("Converted double: " + x);
        
        Boolean booleanObj2 = new Boolean(false);
        boolean y = booleanObj2.booleanValue();
        System.out.println("Converted boolean: " + y);
    }
}

Output:

Converted integer: 123
Converted Double: 3.14
Converted Boolean: true
Converted int: 456
Converted double: 1.23
Converted boolean: false

Explanation:

The program demonstrates how to convert primitive types to objects using the valueOf method of the corresponding wrapper class. For example, to convert an int value to an Integer object, we can use the Integer.valueOf(i) method. Similarly, to convert a double value to a Double object, we can use the Double.valueOf(d) method, and to convert a boolean value to a Boolean object, we can use the Boolean.valueOf(b) method.

The program also demonstrates how to convert objects to primitive types using the intValue, doubleValue, and booleanValue methods of the corresponding wrapper class. For example, to convert an Integer object to an int value, we can use the integerObj.intValue() method. Similarly, to convert a Double object to a double value, we can use the doubleObj2.doubleValue() method, and to convert a Boolean object to a boolean value, we can use the booleanObj2.booleanValue() method.