Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Object.toString()

Returns a text form of the object; called when printing and when concatenating with a string.

Available since: Java 1.0

Syntax

public String toString()

Return value

StringA string. By default, the class name, @ and the hash code in hex.

Examples

A custom toString() makes the output readable:

class User {
    String name;
    int age;
 
    User(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    @Override
    public String toString() {
        return "User{name=" + name + ", age=" + age + "}";
    }
}
 
void main() {
    var user = new User("Anna", 30);
    IO.println(user);
    IO.println("Created: " + user);
    IO.println(List.of(user));
}

Output:

User{name=Anna, age=30}
Created: User{name=Anna, age=30}
[User{name=Anna, age=30}]

Notes

Without an override you get something like User@5ca881b5. IO.println(), string concatenation and collection toString() call the method for you. Records, collections, StringBuilder and dates already have a readable toString(), but arrays do not: use Arrays.toString().

See also

  • String.valueOf() — Converts a value of any type to a string.
  • record — Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().
  • Arrays.toString() — Returns the contents of an array as a string like [1, 2, 3].

Related recipes

In the tutorial

  • Methods of the Object class — The toString, equals and hashCode methods in Java: how to override them and why equals and hashCode always change together.

Thanks for reading!

Donate to the site — we work hard for you.