Menu
Topics Index
...
`

ConstructorsDemo - Java Example Program


ConstructorsDemo
class ConstructorsDemo
{
    public static void main(String[] args)
    {
        Byte b = new Byte((byte) 5); // LINE A
        Byte b_str = new Byte("5" + 1);
        System.out.println("Value of b : " + b + " Value of b_str " + b_str);
        Short s = new Short((short) 10); // LINE B
        Short s_str = new Short("10" + 2);
        System.out.println("Value of s : " + s + " Value of b_str " + s_str);
        Integer i = new Integer(15); // LINE C
        Integer i_str = new Integer("15" + 3);
        System.out.println("Value of i : " + i + " Value of b_str " + i_str);
        Long l = new Long(20); // LINE D
        Long l_str = new Long("20" + 4);
        System.out.println("Value of i : " + l + " Value of b_str " + l_str);
    }
}
OUTPUT

Value of b : 5 Value of b_str 51
Value of s : 10 Value of b_str 102
Value of i : 15 Value of b_str 153
Value of i : 20 Value of b_str 204

DESCRIPTION

In the above program we have created objects for all the wrapper classes using the constructors. At LINE A we have created numeric and String objects for Byte class. In the same way we have created numeric and String objects for Short, Integer, Long classes at LINE B, LINE C, LINE D.

THINGS TO TRY
  • Remove the type casting byte at LINE A to see a compilation error because by default java considers all whole numbers as integers.
  • Replace the line after LINE A with the below code.
    Byte b_str = new Byte("5" + 1 + 2);
    A run time error Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"512" Radix:10 is thrown, since the maximum value for byte is 127 and 512 is greater than 127.

© meritcampus 2019

All Rights Reserved.

Open In App