Menu
Topics Index
...
`

valueOf Test - Java Example Program


valueOf Test
class ValueOfDemo
{
    public static void main(String arg[])
    {
        int i = 10;
        boolean b = true;
        float f = 4.56789f;
        char[] data = {'M','E','R','I','T',' ','C','A','M','P','U','S'};
        String sample = String.valueOf(i); // LINE A
        System.out.println("String of integer i : " + sample);
        sample = String.valueOf(b); // LINE B
        System.out.println("String of boolean b : " + sample);
        sample = String.valueOf(f); // LINE C
        System.out.println("String of float f : " + sample);
        sample = String.valueOf(data, 0, 12); // LINE D
        System.out.println("String representation of data : "+ sample);
        sample = String.valueOf(data, 0, 5); // LINE E
        System.out.println("Subarray in data starting at index 0 : " + sample);
        sample = String.valueOf(data, 6, 6); // LINE F
        System.out.println("Subarray in data starting at index 6 : " + sample);    
    }
}
OUTPUT

String of integer i : 10
String of boolean b : true
String of float f : 4.56789
String representation of data : MERIT CAMPUS
Subarray in data starting at index 0 : MERIT
Subarray in data starting at index 6 : CAMPUS

DESCRIPTION

At LINE A, int is converted to String. At LINE B, boolean is converted to String. At LINE C, float is converted to String. At LINE D, character array data is converted to string using valueOf method. At LINE E, a part of array data is converted to String i.e. 5 characters from index 0. At LINE F, a part of array data is converted to String i.e. 6 characters from index 6.

THINGS TO TRY
  • Try converting other data types like char, double, long, Object.
  • Insert
    sample = String.valueOf(null);
    This statement calls valueOf(char[]) method, which generates a NullPointerException.
  • Insert
    sample = String.valueOf( (Object)null);
    This statement calls valueOf(Object) method. A String object having value null is returned.

© meritcampus 2019

All Rights Reserved.

Open In App