What is toString() and why override it?
Why Interviewers Ask This
This is a classic screening question for OOP Concepts roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
Answer
The toString() method returns a string representation of an object. It's defined in the Object class (the root of all Java classes) and is automatically called when you print an object or concatenate it with a string. Default behavior: class Point { int x, y; } Point p = new Point(); System.out.println(p); // Prints: "Point@1b6d3586" -- useless! // ClassName@hexHashCode -- not meaningful for debugging. Overriding toString(): class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Point(" + x + ", " + y + ")"; } } Point p = new Point(3, 4); System.out.println(p); // "Point(3, 4)" -- meaningful! System.out.println("Location: " + p); // Auto-calls toString() logger.debug("Current position: {}", p); // Also calls toString(). Why override: (1) Debugging — immediately see object state in logs and debugger; (2) Logging — meaningful log messages; (3) Error messages — describe objects in exceptions; (4) Display — show object to users. Best practices for toString(): include the most important fields; don't include sensitive data (passwords, credit card numbers); be concise but informative; use established formats: @Override public String toString() { return "User{id=" + id + ", name='" + name + "', email='" + email + "'}"; }. Libraries: Lombok @ToString, Apache Commons ToStringBuilder, Google Guava Objects.toStringHelper(). @Override annotation ensures you're actually overriding, not creating a new method.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your OOP Concepts experience.