String.valueOf()
Converts a value of any type to a string.
Available since: Java 1.0
Syntax
static String valueOf(Object obj)Parameters
| Parameter | Type | Description |
|---|---|---|
| obj | Object | A number, a char, a boolean, a char[] array or any object. |
Return value
StringThe string form of the value. For null it is the string null.
Examples
Numbers and other values to a string:
void main() {
String a = String.valueOf(42);
String b = String.valueOf(3.5);
String c = String.valueOf(true);
IO.println(a + b + c);
IO.println(a.length());
}Output:
423.5true
2Unlike toString(), it does not fail on null:
void main() {
Object value = null;
IO.println(String.valueOf(value));
}Output:
nullNotes
The reverse conversion is Integer.parseInt(), Double.parseDouble(). A shortcut to turn a number into a string is adding an empty string: "" + 42, but String.valueOf() states the intent more clearly.
See also
- Integer.parseInt() — Converts a string containing an integer to an int.
- Object.toString() — Returns a text form of the object; called when printing and when concatenating with a string.
- String.toCharArray() — Copies the characters of a string into a new char[] array.
Related recipes
In the tutorial
- Type conversion — Automatic widening, explicit (int) casts, turning strings into numbers with Integer.parseInt and numbers into strings.