The String.valueOf() method returns the string representation of any passed argument, including primitives, arrays, and objects.
Static Factory & Null-Safe Conversion: Unlike calling toString() on a null variable which throws NullPointerException, String.valueOf() safely returns "null". For char arrays, it behaves identically to copyValueOf(). To convert strings back into arrays, see toCharArray(). For template formatting, see format(), or join text with concat().
Java defines nine static overloaded methods in java.lang.String to handle every data type:
// 9 Overloaded static signatures of valueOf() in java.lang.String
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)
| Signature | Target Type | Description & Operational Rule |
|---|---|---|
valueOf(Object obj) |
Any Object Reference | Returns "null" if obj == null; otherwise calls obj.toString(). |
valueOf(char[] data) |
Character Array | Converts all array elements into a string (equivalent to copyValueOf()). |
valueOf(char[] data, int off, int len) |
Subarray Slice | Copies len characters starting at index off. |
valueOf(boolean b) |
boolean primitive |
Returns "true" or "false". |
valueOf(char c) |
char primitive |
Returns a 1-character string containing c. |
valueOf(int i) |
Integers (int, long) | Calls Integer.toString(i) or Long.toString(l). |
valueOf(double d) |
Double / Float | Calls Double.toString(d) or Float.toString(f). |
Converting booleans, characters, integers, and floating-point decimals to strings:
// Converting all Java primitive types to String
String sBool = String.valueOf(true);
String sChar = String.valueOf('Z');
String sInt = String.valueOf(45);
String sDouble = String.valueOf(3.14159);
System.out.println("Boolean: " + sBool);
System.out.println("Integer: " + sInt);
System.out.println("Double: " + sDouble);Terminal Output:
Boolean: true
Integer: 45
Double: 3.14159
Calling toString() on a null variable crashes with NullPointerException. String.valueOf(obj) safely returns the literal string "null":
Object user = null;
// RISKY: user.toString() crashes with NullPointerException!
try {
System.out.println(user.toString());
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException on user.toString()!");
}
// SAFE: String.valueOf(user) safely returns the literal string "null"
String safeText = String.valueOf(user);
System.out.println("Safe value: [" + safeText + "]");Terminal Output:
Caught NullPointerException on user.toString()!
Safe value: [null]
Converting a char[] into a String is functionally identical between valueOf() and copyValueOf():
char[] letters = {'p', 'l', 'u', 's'};
// 1. Convert complete character array
String word = String.valueOf(letters);
System.out.println("Array value: " + word); // plus
// 2. Convert character array slice (offset 1, count 2 -> "lu")
String sub = String.valueOf(letters, 1, 2);
System.out.println("Sub-array: " + sub); // luTerminal Output:
Array value: plus
Sub-array: lu
Comparing explicit conversion against string addition shorthand:
| Approach | Code Readability | Execution Performance |
|---|---|---|
String.valueOf(val) |
High: Explicit factory call expressing intent clearly. | Calls direct wrapper method (e.g. Integer.toString) with minimal overhead. |
"" + val |
Convenient shorthand for scripting and simple debug output. | Compiles to makeConcatWithConstants (Java 9+) or temporary StringBuilder. |
int code = 404;
// 1. Implicit concatenation via "" + code (creates StringBuilder or invokedynamic)
String s1 = "" + code;
// 2. Direct String.valueOf(code) (explicit, clear, and highly efficient)
String s2 = String.valueOf(code);
System.out.println("s1 equals s2? " + s1.equals(s2));Terminal Output:
s1 equals s2? true
Safely recording entity properties without risk of null pointer exceptions:
public class AuditLogger {
public static void logField(String fieldName, Object value) {
// String.valueOf ensures null values never crash logging pipelines
String record = "Field: " + fieldName + " | Value: " + String.valueOf(value);
System.out.println(record);
}
public static void main(String[] args) {
logField("username", "alice");
logField("sessionToken", null);
logField("retryCount", 3);
}
}Terminal Output:
Field: username | Value: alice
Field: sessionToken | Value: null
Field: retryCount | Value: 3
Converting numbers to strings and parsing back to numeric values:
public class NumericRoundTrip {
public static void main(String[] args) {
int initial = 2026;
// Number to String
String text = String.valueOf(initial);
// String back to Number
int parsed = Integer.parseInt(text);
System.out.println("Original: " + initial);
System.out.println("Text: " + text);
System.out.println("Parsed: " + parsed);
}
}Terminal Output:
Original: 2026
Text: 2026
Parsed: 2026
Passing a char[] invokes valueOf(char[]), yielding character text. But if typed as Object (e.g. Object o = new char[]{'a'};), it calls valueOf(Object), printing array memory identity like [C@7a81197d!
While String.valueOf((Object) null) safely returns "null", passing (char[]) null throws an immediate NullPointerException!
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringValueOfFullDemo {
public static void main(String[] args) {
// 1. Primitive conversion
String numStr = String.valueOf(45);
if (numStr.equals("45")) {
System.out.println("Check 1 Passed: Integer primitive converted accurately.");
}
// 2. Null safety guarantee
Object nullObj = null;
if (String.valueOf(nullObj).equals("null")) {
System.out.println("Check 2 Passed: Null reference safely returned 'null'.");
}
// 3. Char array conversion matches copyValueOf
char[] chars = {'j', 'a', 'v', 'a'};
if (String.valueOf(chars).equals(String.copyValueOf(chars))) {
System.out.println("Check 3 Passed: valueOf matches copyValueOf output.");
}
System.out.println("All String.valueOf() verification tests passed successfully!");
}
}Terminal Output:
Check 1 Passed: Integer primitive converted accurately.
Check 2 Passed: Null reference safely returned 'null'.
Check 3 Passed: valueOf matches copyValueOf output.
All String.valueOf() verification tests passed successfully!
For an int primitive, String.valueOf(i) internally calls Integer.toString(i) directly. Both are identical in performance.
Java's specification defines String.valueOf(Object) as (obj == null) ? "null" : obj.toString() to provide null-safe logging and concatenation.
Use String.valueOf(charArray) or String.copyValueOf(charArray).
Yes. Passing any custom object invokes its overridden toString() method automatically.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.