Menu
Topics Index
...
`

ByteDemo - Java Example Program


ByteDemo
class ByteDemo
{
    public static void main(String[] args)
    {
        Byte b = new Byte((byte) 2);
        System.out.println("Returns double value: " + b.doubleValue());
        System.out.println("Returns float value: " + b.floatValue());
        System.out.println("Returns long value " + b.longValue());
        System.out.println("Returns int value: " + b.intValue());
        Integer i = new Integer(2); // LINE A
        System.out.println("Compares the value: " + b.equals(i)); // LINE B
        System.out.println("Returns String object: " + b.toString());
        System.out.println("Byte equivalent String: " + Byte.toString((byte) 520));
        //520 - 256 = 264 -> 264 - 256 = 8 which is in byte range
        System.out.println("Decimal equivalent String: " + Byte.parseByte("25", 8)); // LINE C
        //Converts the value of given radix to a byte value.
        System.out.println("Returns Byte object: " + Byte.valueOf("32", 8)); // LINE D
    }
}
OUTPUT

Returns double value: 2.0
Returns float value: 2.0
Returns long value 2
Returns int value: 2
Compares the value: false
Returns String object: 2
Byte equivalent String: 8
Decimal equivalent String: 21
Returns Byte object: 26

DESCRIPTION

In the above program we have used the Byte methods which we are shown in the above table. At LINE B we are comparing the value of Byte object b with Integer object i which results true in the output, since both have same value. At LINE C we are converting the value 10110 of radix 2 to Byte value of radix 10. At LINE D we are converting a String value of given radix to Byte value which throws a NumberFormatException when passed parameter is not a numeric value.

THINGS TO TRY
  • At LINE A in the program change the value of the i to 10 due to which the statement at LINE B results false.
  • At LINE C in the program change the parameters 10110 and 2 to 25 and 8 which result in the output of 21. Here the value 25 of radix 8 is converted to the byte value of radix 10.
  • At LINE D change the value of 321 to Hai to see NumberFormatException.

© meritcampus 2019

All Rights Reserved.

Open In App