Menu
Topics Index
...
`

DoubleDemo - Java Example Program


DoubleDemo
class DoubleDemo
{
    public static void main(String arg[])
    {
        Double d = new Double(9.4);
        /*double prim_d = d; // LINE A
        System.out.println("Value converted to double: " + prim_d);*/
        byte b = d.byteValue(); // LINE B
        System.out.println("Value when converted to bye: " + b);
        int i = d.intValue(); // LINE C
        System.out.println("Value when converted to int: " + i);
        short st = d.shortValue(); // LINE D
        System.out.println("Value when converted to short: " + st);
        long l = d.longValue(); // LINE E
        System.out.println("Value when converted to long: " + l);
        String s = d.toString(); // LINE F
        System.out.println("Value when converted to String: " + s);
        double d1 = Double.parseDouble(s); // LINE G
        System.out.println("Converting String to double: " + d1);    
    }
}
OUTPUT

Value when converted to bye: 9
Value when converted to int: 9
Value when converted to short: 9
Value when converted to long: 9
Value when converted to String: 9.4
Converting String to double: 9.4

DESCRIPTION

At LINE B we have converted Double object d to primitive data type byte. At LINE C we have converted Double object d to primitive data type int. At LINE D we have converted Double object d to primitive data type short. At LINE E we have converted Double object d to primitive data type long. At LINE F we have converted Double object d to String s. At LINE G we have converted String object s to primitive data type double. Things to try Things to try

THINGS TO TRY
  • Replace the code at LINE A with below code.
    byte b1 = (byte)d;
    The above code line gives a compilation error since type casting cannot be performed on an object.
  • Uncomment the code at LINE A and check the output. The output will be Value converted to double: 9.4. Since each time when a value is assigned to a primitive data type JVM creates a wrapper class object for corresponding primitive data type.

© meritcampus 2019

All Rights Reserved.

Open In App