Java String valueOf() method returns the String representation of the boolean, char, char array, int, long, float and double arguments. We have different versions of this method for each type of arguments.
Different variants of java string valueOf() method
public static String valueOf(boolean b): Used for converting boolean value to a String public static String valueOf(char c): char to String public static String valueOf(int i): int to String public static String valueOf(long l): long to String public static String valueOf(float f): float to String public static String valueOf(double d): double to String
Java String valueOf() simple example
Lets take a simple example to understand the usage of this method. In this example we are concatenating the double nines to the end of the given value. The given value is an integer, in order to append 99 at the end of the integer we must need to convert the given integer to the string first. We are using valueOf() method to convert the number
to the equivalent string str
and then we are concatenating the 99 at the end of converted string.
public class JavaExample{ public static void main(String args[]){ int number = 23; String str = String.valueOf(number); System.out.println(str+99); } }
Output:
Method valueOf() example 2
In this example, we are converting an array to a string using valueOf() method.
public class JavaExample{ public static void main(String args[]){ char vowel[] = {'A', 'E', 'I', 'O', 'U'}; String str = String.valueOf(vowel); System.out.println(str); } }
Output:
Java String valueOf() Example
Lets take an example, where we are using all the variants of valueOf() method. In this example we are using valueOf() method to convert the integer, float, long, double, char and char array to the String.
public class Example{ public static void main(String args[]){ int i = 10; //int value float f = 10.10f; //float value long l = 111L; //long value double d = 2222.22; //double value char ch = 'A'; //char value char array[] = {'a', 'b', 'c'}; //char array //converting int to String String str1 = String.valueOf(i); //converting float to String String str2 = String.valueOf(f); //converting long to String String str3 = String.valueOf(l); //converting double to String String str4 = String.valueOf(d); //converting char to String String str5 = String.valueOf(ch); //converting char array to String String str6 = String.valueOf(array); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); System.out.println(str5); System.out.println(str6); } }
Output:
10 10.1 111 2222.22 A abc
Reference: String valueOf() method – JavaDoc
Leave a Reply