Course – LS – All

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

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll explore various techniques for converting an object to its string representation in Java.

Converting an object to a string is essential for a multitude of reasons, ranging from displaying object information in a user-friendly format to persisting object data in a readable form.

2. Using toString()

The most straightforward way to convert an object to a string is by using the toString() method. toString() is a built-in method provided by the Object class, which is the root class for all Java objects. Therefore, this method is inherited by all classes, and it returns a String representation of the object.

However, the default implementation of toString() in the Object class isn’t very informative, as it returns a string that includes the object’s hash code, like, com.baeldung.objecttostring.Person@1f2a0679.

To make this method more useful for our own custom classes, we can override it. By providing our own implementation, we can return a String that represents the object’s data and attributes in a human-readable form.

Here’s an example of how we can override the toString() method in a custom class:

public class Person {
    private String name;
    private int age;
    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

In this example, the Person class overrides the toString() method to return a String containing the person’s name and age. We can use the toString() method by calling it on an object:

@Test
public void givenObject_whenToString_thenConvert() {
    Person person = new Person("Sarah", 28);
    String expected = "Person{name='Sarah', age=28}";
    String actual = person.toString();
    assertEquals(expected, actual);
}

3. Using String.valueOf()

Another simple way to convert an object to a String is by using the String.valueOf() method. This is a static method provided by the String class, which is used to return a string that represents the specified value. This method accepts an object as its argument and returns the string representation of that object. If the object is null, it returns the string “null.

Here’s an example of using String.valueOf():

@Test
public void givenObject_whenValueOf_thenConvert() {
    Person person = new Person("Sarah", 28);
    String expected = "Person{name='Sarah', age=28}";
    String actual = String.valueOf(person);
    assertEquals(expected, actual);
}

This results in the string representation of the person object.

4. Using Concatenation

We can also convert an object to a String through the technique of String concatenation. When an object is joined with an empty string using the addition (+) operator, it yields its string representation:

@Test
public void givenObject_whenConcat_thenConvert() {
    Person person = new Person("Sarah", 28);
    String expected = "Person{name='Sarah', age=28}";
    String actual = "" + person;
    assertEquals(expected, actual);
}

5. Using commons-lang3 Library

The Apache Commons Lang 3 library offers functionality for the manipulation of fundamental Java API classes. To utilize the Commons Lang 3 library, we simply retrieve it from the central Maven repository by adding the following dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

We can use the ToStringBuilder class from this library to build a custom string representation for an object. The ToStringBuilder class allows us to specify which fields of our object we want to include in the string representation.

Here’s an example of how to use ToStringBuilder to convert an object to a String:

public class Person {
    private String name;
    private int age;

    public String toCustomString() {
        return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
          .append("name", name)
          .append("age", age)
          .toString();
    }
}

In this example, we use ToStringBuilder to create a custom string representation for the Person object in the toCustomString() method. We specify the fields we want to include and the ToStringStyle (e.g., ToStringStyle.JSON_STYLE) for formatting the output:

@Test
public void givenObject_whenToStringBuilder_thenConvert() {
    Person person = new Person("Sarah", 28);
    String expected = "{\"name\":\"Sarah\",\"age\":28}";
    String actual = person.toCustomString();
    assertEquals(expected, actual);
}

6. Conclusion

In this article, we’ve explored several methods for converting an object to a String in Java.

The choice of method depends on the specific requirements and the complexity of the object we’re working with. It’s crucial to verify that the resulting string effectively conveys the object’s data and aligns with our intended use. With the right approach, we can seamlessly convert objects to strings and improve the readability and usability of our Java applications.

As always, the full source code is available over on GitHub.

Course – LS – All

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

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.