Java Top

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

Every class in Java is a child of the Object class either directly or indirectly. And since the Object class contains a toString() method, we can call toString() on any instance and get its string representation.

In this tutorial, we’ll look at the default behavior of toString() and learn how to change its behavior.

2. Default Behavior

Whenever we print an object reference, it invokes the toString() method internally. So, if we don’t define a toString() method in our class, then Object#toString() is invoked.

Object’s toString() method is pretty generic:

public String toString() {
    return getClass().getName()+"@"+Integer.toHexString(hashCode());
}

To see how this works, let’s create a Customer object that we’ll use throughout our tutorial:

public class Customer {
    private String firstName;
    private String lastName;
    // standard getters and setters. No toString() implementation
}

Now, if we try to print our Customer object, Object#toString() will be called, and the output will be similar to:

[email protected]

3. Overriding Default Behavior

Looking at the above output, we can see that it doesn’t give us much information about the contents of our Customer object. Generally, we aren’t interested in knowing the hashcode of an object, but rather the contents of our object’s attributes.

By overriding the default behavior of the toString() method, we can make the output of the method call more meaningful.

Now, let’s look at a few different scenarios using objects to see how we can override this default behavior.

4. Primitive Types and Strings

Our Customer object has both String and primitive attributes. We need to override the toString() method to achieve a more meaningful output:

public class CustomerPrimitiveToString extends Customer {
    private long balance;

    @Override
    public String toString() {
        return "Customer [balance=" + balance + ", getFirstName()=" + getFirstName()
          + ", getLastName()=" + getLastName() + "]";
    }
}

Let’s see what we get when we call toString() now:

@Test
public void givenPrimitive_whenToString_thenCustomerDetails() {
    CustomerPrimitiveToString customer = new CustomerPrimitiveToString();
    customer.setFirstName("Rajesh");
    customer.setLastName("Bhojwani");
    customer.setBalance(110);
    assertEquals("Customer [balance=110, getFirstName()=Rajesh, getLastName()=Bhojwani]", 
      customer.toString());
}

5. Complex Java Objects

Let’s now consider a scenario where our Customer object also contains an order attribute that is of type Order. Our Order class has both String and primitive data type fields.

So, let’s override toString() again:

public class CustomerComplexObjectToString extends Customer {
    private Order order;
    //standard setters and getters
    
    @Override
    public String toString() {
        return "Customer [order=" + order + ", getFirstName()=" + getFirstName()
          + ", getLastName()=" + getLastName() + "]";
    }      
}

Since order is a complex object, if we just print our Customer object, without overriding the toString() method in our Order class, it will print orders as [email protected]<hashcode>.

To fix that let’s override toString() in Order, too:

public class Order {
    
    private String orderId;
    private String desc;
    private long value;
    private String status;
 
    @Override
    public String toString() {
        return "Order [orderId=" + orderId + ", desc=" + desc + ", value=" + value + "]";
    }
}

Now, let’s see what happens when we call the toString() method on our Customer object that contains an order attribute:

@Test
public void givenComplex_whenToString_thenCustomerDetails() {
    CustomerComplexObjectToString customer = new CustomerComplexObjectToString();    
    // .. set up customer as before
    Order order = new Order();
    order.setOrderId("A1111");
    order.setDesc("Game");
    order.setStatus("In-Shiping");
    customer.setOrders(order);
        
    assertEquals("Customer [order=Order [orderId=A1111, desc=Game, value=0], " +
      "getFirstName()=Rajesh, getLastName()=Bhojwani]", customer.toString());
}

6. Array of Objects

Next, let’s change our Customer to have an array of Orders. If we just print our Customer object, without special handling for our orders object, it will print orders as Order;@<hashcode>.

To fix that let’s use Arrays.toString() for the orders field:

public class CustomerArrayToString  extends Customer {
    private Order[] orders;

    @Override
    public String toString() {
        return "Customer [orders=" + Arrays.toString(orders) 
          + ", getFirstName()=" + getFirstName()
          + ", getLastName()=" + getLastName() + "]";
    }    
}

Let’s see the results of calling the above toString() method:

@Test
public void givenArray_whenToString_thenCustomerDetails() {
    CustomerArrayToString customer = new CustomerArrayToString();
    // .. set up customer as before
    // .. set up order as before
    customer.setOrders(new Order[] { order });         
    
    assertEquals("Customer [orders=[Order [orderId=A1111, desc=Game, value=0]], " +
      "getFirstName()=Rajesh, getLastName()=Bhojwani]", customer.toString());
}

7. Wrappers, Collections, and StringBuffers

When an object is made up entirely of wrappers, collections, or StringBuffers, no custom toString() implementation is required because these objects have already overridden the toString() method with meaningful representations:

public class CustomerWrapperCollectionToString extends Customer {
    private Integer score; // Wrapper class object
    private List<String> orders; // Collection object
    private StringBuffer fullname; // StringBuffer object
  
    @Override
    public String toString() {
        return "Customer [score=" + score + ", orders=" + orders + ", fullname=" + fullname
          + ", getFirstName()=" + getFirstName() + ", getLastName()=" + getLastName() + "]";
    }
}

Let’s again see the results of calling toString():

@Test
public void givenWrapperCollectionStrBuffer_whenToString_thenCustomerDetails() {
    CustomerWrapperCollectionToString customer = new CustomerWrapperCollectionToString();
    // .. set up customer as before
    // .. set up orders as before 
    customer.setOrders(new Order[] { order }); 
    
    StringBuffer fullname = new StringBuffer();
    fullname.append(customer.getLastName()+ ", " + customer.getFirstName());
    
    assertEquals("Customer [score=8, orders=[Book, Pen], fullname=Bhojwani, Rajesh, getFirstName()=Rajesh, "
      + "getLastName()=Bhojwani]", customer.toString());
}

8. Conclusion

In this article, we looked at creating our own implementations of the toString() method.

All of the source code for this article is available over on GitHub.

Java bottom

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Eric MartinCililing Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Cililing
Guest
Cililing

Nice article, but I would mention about generators included in most of IDEs. They are able to generate toString and some more methods with 2-3 clicks.

Also, in Kotlin there is special keyword “data” for class with default nicely formatted toString 😀

Eric Martin
Member
Eric Martin

Good points.

I’m also a fan of Lombok’s @ToString annotation.
https://www.baeldung.com/intro-to-project-lombok