Core Java

ToString Java Example

In this article we will learn about the toString Java method in Object class.

1. Introduction

The toString() method in the Object class returns a string representation of the object. In general, the toString() method returns a string that “textually represents” this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

In Java, the toString() method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character ‘@’, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

2. ToString Java Code

In this section we will write some code and will see how the toString() method behaves in different cases. First, we will create a Person class with has some basic fields like firstName, surname etc.

Person.java

public class Person {

    private String firstName;
    private String surname;
    private Address address;
    private String[] otherNames;

The Person class had a reference to another class called Address which represents the address of the person. It also has an array of String representing the other names of the person. Below we show the snippet of Address class.

Address.java

public class Address {

    private String firstLine;
    private String secondLine;
    private String city;
    private String country;

Now we will create a very simple main class that will print the value returned from toString() method of Person class. Please note we have not overridden the toString() method yet.

public class ToStringExample {

    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.toString());
    }
}

If you run this class you will see the result as below:

com.javacodegeeks.Person@60e53b93

2.1 Override toString()

In this section we will see how to override the toString() method and what difference it makes to the output. Let’s first override the toString() method in Person class like below:

    @Override
    public String toString() {
        return "Person{" +
                "firstName='" + firstName + '\'' +
                ", surname='" + surname + '\'' +
                ", address=" + address +
                ", otherNames=" + otherNames +
                '}';
    }

Now change the ToStringExample class to create the object of Person class and print the object:

ToStringExample.java

public class ToStringExample {

    public static void main(String[] args) {
        Person person = new Person("Michael"
                , "Jackson"
                , new Address("222 Elezabeth Road", "Hololulu", "London", "China")
                , new String[] {"Other name 1", "Otherr name 2"});
        System.out.println(person.toString());
    }
}

Now when you run the class you will see:

Person{firstName='Michael', surname='Jackson', address=com.javacodegeeks.Address@60e53b93, otherNames=[Ljava.lang.String;@5e2de80c}

We can see that the first name and surname are printed correctly but the Address and other names are not. The reason that the address is not displayed correctly is that we have not overridden the toString() method of the Address class. The reason why other names are not displayed correctly is because array is an object in java so we have to manually change the behaviour.

Let’s override the toString() method of Addess class like below:

    @Override
    public String toString() {
        return "Address{" +
                "firstLine='" + firstLine + '\'' +
                ", secondLine='" + secondLine + '\'' +
                ", city='" + city + '\'' +
                ", country='" + country + '\'' +
                '}';
    }

Modify the toString() method of Person class like below:

@Override
    public String toString() {
        return "Person{" +
                "firstName='" + firstName + '\'' +
                ", surname='" + surname + '\'' +
                ", address=" + address +
                ", otherNames=" + Arrays.toString(otherNames) +
                '}';
    }

Now run the ToStringExample class

Person{firstName='Michael', surname='Jackson', address=Address{firstLine='222 Elezabeth Road', secondLine='Hololulu', city='London', country='China'}, otherNames=[Other name 1, Otherr name 2]}

3. Wrapper and Collection Classes

In this section we will see that the toString() method in the wrapper and collection classes are already implemented.

Let’s look at our first example – Integer class. The Integer wrapper class implements the toString() method. Let see an example

Integer integer = new Integer(39);
System.out.println(integer);

When we run the example above we will see it prints 39. Now we will do the same for the other wrapper classes as below:

Integer integer = new Integer(39);
System.out.println(integer);
Long longNumber = new Long(40);
System.out.println(longNumber);
Float flotingNumber = new Float(41);
System.out.println(flotingNumber);
Double doubleNumber = new Double(42);
System.out.println(doubleNumber);
Character character = new Character('q');
System.out.println(character);

Now we will look into Collection classes. Let us take the example of ArrayList. We will add the Person objects in the list and will print the list.

Person person1 = new Person("Michael"
        , "Jackson"
        , new Address("222 Elezabeth Road", "Hololulu", "London", "China")
        , new String[] {"Other name 1", "Otherr name 2"});
Person person2 = new Person("Tom"
        , "Cruise"
        , new Address("221 Elezabeth Road", "Hololulu", "London", "China")
        , new String[] {"Other name 3", "Otherr name 4"});
List personList = new ArrayList();
personList.add(person1);
personList.add(person2);
System.out.println(personList);

When we run this program we will get the below output:

[Person{firstName='Michael', surname='Jackson', address=Address{firstLine='222 Elezabeth Road', secondLine='Hololulu', city='London', country='China'}, otherNames=[Other name 1, Otherr name 2]}, Person{firstName='Tom', surname='Cruise', address=Address{firstLine='221 Elezabeth Road', secondLine='Hololulu', city='London', country='China'}, otherNames=[Other name 3, Otherr name 4]}]

All these Collection classes extends the java.util.AbstractCollection which implements the toString() method. The toString() method returns a string representation of this collection. The string representation consists of a list of the collection’s elements in the order they are returned by its iterator, enclosed in square brackets “[]”. Adjacent elements are separated by the characters “, ” (comma and space). Elements are converted to strings as by String#valueOf(Object).

4. Conclusion

In this article we learned about the toString() method in the Object class. We discussed when it is important to implement this method and in which cases it is useful to do that. We also looked that the standard wrapper classes in java have already got this method implemented so we don’t have to implement it again. Also, the Collection classes have the toString() method implemented in the java.util.AbstractCollection.

5. Download the source code

Download
You can download the full source code of this example here: ToString Java Example

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button