Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:


1. Overview

Manipulating Strings is a fundamental task when we work with Java. We often need to convert other data types into Strings. Two common approaches for accomplishing this are casting to String and using the String.valueOf() method. They might seem similar on the surface, but some differences between the two methods may affect our code’s behavior.

In this quick tutorial, let’s discuss the differences between them.

2. Casting to String and String.valueOf()

First, let’s look at an example. Let’s say we assigned a String value to a variable with the type Object:

Object obj = "Baeldung is awesome!";

If we want to convert obj to a String, we can cast directly:

String castResult = (String) obj;
assertEquals("Baeldung is awesome!", castResult);

Alternatively, we can use the String.valueOf() method offered by the standard library:

String valueOfResult = String.valueOf(obj);
assertEquals("Baeldung is awesome!", valueOfResult);

As we can see, both approaches work as expected.

Although the two approaches may appear similar at first glance, they actually have some notable differences.

Next, let’s delve into them.

3. When Converting Non-String Objects

We just now assigned a String value to an Object variable. Casting to String and String.valueOf() can convert obj to a String instance.

Next, let’s assign some non-string values to Object variables and see if they still work as expected.

First, let’s test direct casting the non-string object to String:

Object obj = 42;
assertThrows(ClassCastException.class, () -> {String castResult = (String) obj;});
Object obj2 = List.of("Baeldung", "is", "awesome");
assertThrows(ClassCastException.class, () -> {String castResult = (String) obj2;});

In the example above, we assigned an integer value (42) to obj, while obj2 holds a List of String values. As demonstrated, direct casting to String throws ClassCastException when the object isn’t of type String. This is straightforward to grasp: since String is a final class, casting to String is valid only if we know the object is a String or null.

Next, let’s see if the String.valueOf() method throws the same exception:

String valueOfResult = String.valueOf(obj);
assertEquals("42", valueOfResult);
valueOfResult = String.valueOf(obj2);
assertEquals("[Baeldung, is, awesome]", valueOfResult);

As we can see, when we pass obj and obj2 to String.valueOf(), it doesn’t throw any exception. Instead, it converts non-string objects to String values.

Next, let’s look at String.valueOf()‘s implementation to figure out why this happened:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();

The implementation is indeed straightforward. The String.valueOf() method invokes the toString() method of the input obj. Consequently, it always returns a String, regardless of whether obj is of type String or not.

Moreover, as evident from the implementation of String.valueOf(), the method includes a null-check. So next, let’s examine how direct casting and String.valueOf() handle null values.

4. Handling null Values

Let’s first try to cast a null object to String:

Object obj = null;
String castResult = (String) obj;

As the example shows, we get a null value by casting a null value to String.

Since we’ve seen the implementation of the String.valueOf() method, the test result won’t be surprising:

String valueOfResult = String.valueOf(obj);
assertEquals("null", valueOfResult);

Unlike direct casting, String.valueOf() never returns null. We get the Stringnull” if we pass a null value to String.valueOf().

5. Conclusion

Both casting to String and using String.valueOf() can convert non-string data types to String values in Java. In this article, we explored the differences between them.

Next, let’s briefly summarize their key differences:

  • Type Flexibility – String.valueOf() accepts inputs of any type and returns their String representations without raising exceptions. Casting, on the other hand, is limited to String values that are referenced by String or a supertype, such as CharSequence, Object, etc, leading to ClassCastException when used incorrectly.
  • null Handling – String.valueOf() gracefully handles null values, converting them to the string “null.” Casting to String returns null if the object being cast is null.
  • Readability – String.valueOf() is more explicit in its purpose, making the code easier to understand. However, casting to a String might be less clear and can be misinterpreted as an attempt to typecast rather than a conversion to a String.

Therefore, the String.valueOf() method provides a more robust solution for converting different data types to Strings.

As always, the complete source code for the examples is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

res – REST with Spring (eBook) (everywhere)
Notify of
Inline Feedbacks
View all comments