Java String.valueOf
Convert a primitive, an object or character-array data into a String using the selected overload.
A simple example
String.valueOf
- Start with The integer 2
- Do this Convert to text
- Result "2"
class Main {
public static void main(String[] args) throws Exception {
System.out.println(String.valueOf(2));
}
}
2
Syntax
public static String valueOf(Object obj)
JDK 21 method signatures (9)
public static String valueOf(Object obj)
public static String valueOf(char[] data)
public static String valueOf(char[] data, int offset, int count)
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPrint the count of remaining seats
The booking screen keeps a numeric count internally and prints it beside a text label. Convert at display time so the same count remains available for arithmetic when another booking is made.
class Main {
public static void main(String[] args) throws Exception {
int seats = 12;
System.out.println("Seats: " + String.valueOf(seats));
}
}
Seats: 12
The integer overload produces decimal digits suitable for the label.
Understand a missing optional note
An optional field may be absent when a receipt or notice is displayed. Decide what that missing value should look like on the screen before treating the converted text as a user-supplied note.
class Main {
public static void main(String[] args) throws Exception {
Object note = null;
System.out.println("[" + String.valueOf(note) + "]");
}
}
[null]
A null Object becomes four printable letters. Replace it deliberately if a blank display is preferable.
Print the first entry tag
A coat-check desk numbers the first ticket one. The ticket printer includes the number as ordinary decimal text after a prefix. What does the completed label say?
What to watch for
Calling valueOf on a null Object returns the text null. A null char array selects a different overload and throws.