Categories
java object string tostring

How do I print my Java object without getting “[email protected]”?

382

I have a class defined as follows:

public class Person {
  private String name;

  // constructor and getter/setter omitted
}

I tried to print an instance of my class:

System.out.println(myPerson);

but I got the following output: [email protected].

A similar thing happened when I tried to print an array of Person objects:

Person[] people = //...
System.out.println(people); 

I got the output: [Lcom.foo.Person;@28a418fc

What does this output mean? How do I change this output so it contains the name of my person? And how do I print collections of my objects?

Note: this is intended as a canonical Q&A about this subject.

2

487

Background

All Java objects have a toString() method, which is invoked when you try to print the object.

System.out.println(myObject);  // invokes myObject.toString()

This method is defined in the Object class (the superclass of all Java objects). The Object.toString() method returns a fairly ugly looking string, composed of the name of the class, an @ symbol and the hashcode of the object in hexadecimal. The code for this looks like:

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

A result such as [email protected] can therefore be explained as:

  • com.foo.MyType – the name of the class, i.e. the class is MyType in the package com.foo.
  • @ – joins the string together
  • 2f92e0f4 the hashcode of the object.

The name of array classes look a little different, which is explained well in the Javadocs for Class.getName(). For instance, [Ljava.lang.String means:

  • [ – an single-dimensional array (as opposed to [[ or [[[ etc.)
  • L – the array contains a class or interface
  • java.lang.String – the type of objects in the array

Customizing the Output

To print something different when you call System.out.println(myObject), you must override the toString() method in your own class. Here’s a simple example:

public class Person {

  private String name;
  
  // constructors and other methods omitted
  
  @Override
  public String toString() {
    return name;
  }
}

Now if we print a Person, we see their name rather than [email protected].

Bear in mind that toString() is just one way for an object to be converted to a string. Typically this output should fully describe your object in a clear and concise manner. A better toString() for our Person class might be:

@Override
public String toString() {
  return getClass().getSimpleName() + "[name=" + name + "]";
}

Which would print, e.g., Person[name=Henry]. That’s a really useful piece of data for debugging/testing.

If you want to focus on just one aspect of your object or include a lot of jazzy formatting, you might be better to define a separate method instead, e.g. String toElegantReport() {...}.


Auto-generating the Output

Many IDEs offer support for auto-generating a toString() method, based on the fields in the class. See docs for Eclipse and IntelliJ, for example.

Several popular Java libraries offer this feature as well. Some examples include:


Printing groups of objects

So you’ve created a nice toString() for your class. What happens if that class is placed into an array or a collection?

Arrays

If you have an array of objects, you can call Arrays.toString() to produce a simple representation of the contents of the array. For instance, consider this array of Person objects:

Person[] people = { new Person("Fred"), new Person("Mike") };
System.out.println(Arrays.toString(people));

// Prints: [Fred, Mike]

Note: this is a call to a static method called toString() in the Arrays class, which is different to what we’ve been discussing above.

If you have a multi-dimensional array, you can use Arrays.deepToString() to achieve the same sort of output.

Collections

Most collections will produce a pretty output based on calling .toString() on every element.

List<Person> people = new ArrayList<>();
people.add(new Person("Alice"));
people.add(new Person("Bob"));    
System.out.println(people);

// Prints [Alice, Bob]

So you just need to ensure your list elements define a nice toString() as discussed above.

0

    80

    I think apache provides a better util class which provides a function to get the string

    ReflectionToStringBuilder.toString(object)
    

    2

    • 9

      This has the advantage that it doesn’t require to edit the class, which is sometimes not possible. However, how can I recursively print nested objects too?

      – lukas84

      Mar 23, 2018 at 17:16


    • 3

      @lukas84 ReflectionToStringBuilder.toString(input, new RecursiveToStringStyle()); This will print nested objects as well

      Jun 18, 2021 at 16:53

    39

    Every class in Java has the toString() method in it by default, which is called if you pass some object of that class to System.out.println(). By default, this call returns the [email protected] of that object.

    {
        SomeClass sc = new SomeClass();
        // Class @ followed by hashcode of object in Hexadecimal
        System.out.println(sc);
    }
    

    You can override the toString method of a class to get different output. See this example

    class A {
        String s = "I am just a object";
        @Override
        public String toString()
        {
            return s;
        }
    }
    
    class B {
        public static void main(String args[])
        {
            A obj = new A();
            System.out.println(obj);
        }
    }
    

    1

    • 4

      This is a well-put and short answer, but to clarify why OP is getting [Lcom.foo.Person;@28a418fc as output: that’s the output of toString() method, too, but of the one that is implemented in the class that is generated at runtime for the type Person[], not Person (see stackoverflow.com/a/8546532/1542343).

      – gvlasov

      Mar 24, 2015 at 21:28