Wrapper Class - Converting number object to primitive number in Java


The wrapperClass2 program demonstrates how to convert wrapper objects back to their corresponding primitive types using the valueOf() and xxxValue() methods.

In the program, the following conversions are performed:

  • A Byte object is created with a value of 65 using Byte.valueOf(). The byteValue() method is then called to retrieve the primitive byte value and it is printed to the console.
  • A Short object is created with a value of 25 using Short.valueOf(). The shortValue() method is then called to retrieve the primitive short value and it is printed to the console.
  • An Integer object is created with a value of 45 using Integer.valueOf(). The intValue() method is then called to retrieve the primitive int value and it is printed to the console.
  • A Float object is created with a value of 45.25 using Float.valueOf(). The floatValue() method is then called to retrieve the primitive float value and it is printed to the console.
  • A Long object is created with a value of 1052695 using Long.valueOf(). The longValue() method is then called to retrieve the primitive long value and it is printed to the console.
  • A Double object is created with a value of 45.25 using Double.valueOf(). The doubleValue() method is then called to retrieve the primitive double value and it is printed to the console.

Source Code

public class wrapperClass2 {
    public static void main(String args[])
    {
        //Converting number object to primitive number.
 
       // Byte B= new Byte((byte) 65);
        Byte B= Byte.valueOf((byte) 65);
        byte b= B.byteValue();
        System.out.println(b);
 
        // Short S= new Short((short) 25);
        Short S= Short.valueOf((short) 25);
        short s= S.shortValue();
        System.out.println(s);
 
        // Integer I= new Integer((int) 45);
        Integer I= Integer.valueOf((int) 45);
        int i= I.intValue();
        System.out.println(i);
 
        // Float F= new Float(45.25f);
        Float F= Float.valueOf(45.25f);
        float f= F.floatValue();
        System.out.println(f);
 
        Long L= Long.valueOf(1052695);
        long l= L.longValue();
        System.out.println(l);
 
        Double D= Double.valueOf(45.25);
        double d= D.doubleValue();
        System.out.println(d);
 
    }
}
 

Output

65
25
45
45.25
1052695
45.25
To download raw file Click Here

Basic Programs