toString()
is a method from the Object class that returns a string representation of an object.
By default, it returns: ClassName@HashCode
.
Example
class Car {}
Car car = new Car();
System.out.println(car); // Car@5e2de80c (not helpful)
class Car {
String brand = "BMW";
int year = 2020;
@Override
public String toString() {
return "Car: " + brand + ", Year: " + year;
}
}
Car car = new Car();
System.out.println(car); // "Car: BMW, Year: 2020"
Why Override It?
- Makes logs and debug output readable.
- Easier to test and inspect objects.
- Improves developer experience when printing or logging objects.
toString() in Collections
List<String> list = list.of("A", "B", "C");
System.out.println(list); // [A, B, C]
Java collections override toString()
for human-readable output.
Tip
Mention that overriding
toString()
is a good practice for custom classes - especially for debugging, logging and displaying meaningful information.
Parent: _Strings