Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.valueOf — converting values to text and handling null

Use `String.valueOf` to turn a value into text. Learn why a missing exception message becomes the string `"null"`, while passing the bare `null` literal throws an exception.

Version: Java SE 21

Syntax

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)

In Java SE 21, String.valueOf is a family of static overloads on java.lang.String. The valueOf(Object) overload returns the string "null" when its argument is null. For a non-null object, it returns the result of obj.toString() and does not catch exceptions thrown by that method.

If ex refers to an existing exception, use String.valueOf(ex.getMessage()) to display its message. The return type of getMessage() is String, so the compiler selects the Object overload even when the message is absent. This does not protect against ex == null: the argument is evaluated first. After conversion, a missing message and a message containing exactly "null" are indistinguishable.

Do not use String.valueOf(null) to produce the string "null". The compiler selects char[] over Object because it is more specific, and the call throws NullPointerException. Use String.valueOf((Object) null) to select the Object overload explicitly.

There are separate overloads for the primitive types boolean, char, int, long, float, and double. The char[] overload copies the entire array, while valueOf(data, offset, count) copies count elements starting at the zero-based index offset. Later changes to the array do not change the result. An invalid range throws IndexOutOfBoundsException.

Examples

public class Main {
    public static void main(String[] args) {
        Exception withoutMessage = new Exception();
        Exception withMessage = new Exception("Disk full");

        String missing = String.valueOf(withoutMessage.getMessage());
        String present = String.valueOf(withMessage.getMessage());

        System.out.println("missing: [" + missing + "]");
        System.out.println("present: [" + present + "]");
        System.out.println("missing == null: " + (missing == null));
    }
}

Result

missing: [null]
present: [Disk full]
missing == null: false

`getMessage()` returns `null` for the first exception and `"Disk full"` for the second. The `false` result confirms that `missing` holds the string `"null"`, not a null reference.

Related lessons

  • Java · Lesson 30 · Intermediate · Version: 2

Sources