Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to print an object in a readable form

Short answer

Override toString() — IO.println() and string concatenation call it:

class Product {
    String name = "Tea";
    double price = 3.5;
 
    @Override
    public String toString() {
        return name + " (" + price + " €)";
    }
}
 
void main() {
    IO.println(new Product());
    IO.println("Item: " + new Product());
}

Output:

Tea (3.5 €)
Item: Tea (3.5 €)

Records

Records already have a toString() that shows the type name and all fields:

record User(String name, int age) {}
 
void main() {
    IO.println(new User("Anna", 30));
}

Output:

User[name=Anna, age=30]

Hiding secret fields

Passwords and tokens must not end up in logs. Override the record's toString():

record Credentials(String login, String password) {
    @Override
    public String toString() {
        return "Credentials[login=" + login + ", password=***]";
    }
}
 
void main() {
    IO.println(new Credentials("anna", "s3cret"));
}

Output:

Credentials[login=anna, password=***]

Common mistake

Not overriding toString(). You then get the class name and a hash code, which tell you nothing:

class Product {
    String name = "Tea";
}
 
void main() {
    IO.println(new Product());
}

Output:

Main$Product@2698dc7

The number after @ will be different for you.

Functions used in this recipe

  • Object.toString() — Returns a text form of the object; called when printing and when concatenating with 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].

Thanks for reading!

Donate to the site — we work hard for you.