Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.valueOf(Object): turn an object or null into text

This method returns the text `"null"` for a null reference and delegates to the object's `toString()` otherwise. That rule applies to the `Object` overload.

Version: Java SE 21

Syntax

public static String valueOf(Object obj)

String.valueOf(Object) is a static method of java.lang.String. If the argument is a null reference, the method returns "null", a four-character string, not a null reference. Otherwise, it calls the object's toString() implementation and returns the result unchanged.

Use it to display a candidate or wrong value in a diagnostic message without calling an instance method on a null reference. It is not serialization or a test for missing values: a null reference and the string "null" produce the same text. Check the input before converting if that distinction matters. If toString() returns null or throws an exception, valueOf(Object) does not replace that outcome with the string "null".

The compiler selects the overload using the argument's compile-time type. String.valueOf(null) selects the more specific String.valueOf(char[]) overload and throws NullPointerException. Use String.valueOf((Object) null) or pass an Object variable to select the object overload. With a non-null char[], the array overload copies the characters into a string; passing the same array as an Object calls the array's toString() instead.

Examples

public class Main {
    record Candidate(int score) {
        @Override
        public String toString() {
            return "score=" + score;
        }
    }

    public static void main(String[] args) {
        Object candidate = new Candidate(7);
        Object wrong = null;

        System.out.println("candidate=" + String.valueOf(candidate));
        String wrongText = String.valueOf(wrong);
        System.out.println("wrong is the text null: " + "null".equals(wrongText));
        System.out.println("chars=" + String.valueOf(new char[] {'o', 'k'}));

        try {
            String.valueOf(null);
        } catch (NullPointerException e) {
            System.out.println("bare null: NullPointerException");
        }
    }
}

Result

candidate=score=7
wrong is the text null: true
chars=ok
bare null: NullPointerException

`candidate` uses its own `toString()`, and the comparison confirms that `wrong` becomes the text `"null"`. The character array produces `ok`. The last line comes from the `catch` block after the call with the bare `null` literal.

Related lessons

  • Java · Lesson 58 · Basic · Version: 2
  • Java · Lesson 37 · Intermediate · Version: 2

Sources