Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

We can use the toString() method in Java to return a string representation of an object. Often, it’s overridden to provide a meaningful description of the object’s state. However, certain fields might be null, and printing them could lead to NullPointerExceptions.

In this tutorial, we’ll explore several approaches to handling this scenario by using default values.

2. An Employee Use Case Scenario

Let’s consider that we develop an application that manages employee records. Each employee has attributes such as name, age, and department:

public class Employee {
    private String name;
    private int age;
    private String department;

    public Employee(String name, int age, String department) {
        this.name = name;
        this.age = age;
        this.department = department;
    }
}

In addition, it’s crucial to clearly and informatively represent each Employee object when displaying employee information.

However, in real-world scenarios, an employee’s name and department attributes may sometimes be null, leading to unexpected behavior if not appropriately handled.

3. Null Check Within the toString() Method

One of the simplest approaches is to perform a null check within the toString() method for each field that could potentially be null. If the field is null, we can print a default value instead. Here’s a basic example:

@Override
public String toString() {
    return "Name: " + (name != null ? name : "Unknown") +
      ", Age: " + age +
      ", Department: " + (department != null ? department : "Unknown");
}

In this approach, when a name or department is null, we print “Unknown” instead to prevent displaying null values in the string representation of the Employee object.

4. Using the Optional Class

Java 8 introduced the Optional class, which can be utilized to handle null values more elegantly.

Here’s how it can be done:

@Override
public String toString() {
    return "Name: " + Optional.ofNullable(name).orElse("Unknown") +
      ", Age: " + age +
      ", Department: " + Optional.ofNullable(department).orElse("Unknown");
}

If the name or department is null, we print “Unknown” instead of null using the Optional’s orElse() method.

5. Custom Helper Method

Creating a custom helper method can improve code readability, especially if multiple fields need to be checked for null values. Additionally, this method can encapsulate the null check and default value assignment logic.

Here’s an example:

private String getDefaultIfNull(String value, String defaultValue) {
    return value != null ? value : defaultValue;
}

Here, we create a custom helper method getDefaultIfNull() to handle null values. This method checks if the value is null and returns the default value if it is.

Then, within the toString() method, we utilize the getDefaultIfNull() method to handle null values for each field:

@Override
public String toString() {
    return "Name: " + getDefaultIfNull(name, "Unknown") +
      ", Age: " + age +
      ", Department: " + getDefaultIfNull(department, "Unknown");
}

6. Using the Objects.toString() Method

Java provides a utility method Objects.toString() to handle null values when converting objects to strings:

@Override
public String toString() {
    return "Name: " + Objects.toString(name, "Unknown") +
      ", Age: " + age +
      ", Department: " + Objects.toString(department, "Unknown");
}

In this approach, we utilize the Objects.toString() method to print “Unknown” instead of null if the name or department fields are null.

7. Conclusion

In this article, we discussed overriding the toString() method and handling the potential null within.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW