I recently used a toString() method in one of my projects to organize the output in my console but I was wondering if there is any significance to this method rather than it simply returning a string?
2 Answers
There are several reasons to use a toString() method. The important thing is that all objects have one natively, so it allows you to concatenate an object (such as an Integer) to a string. Sometimes you can do this just by appending an empty string to that object (e.g. "" + my_int
will produce a string) because under the hood Java calls my_int
's toString() method to convert it for you.
It's also useful when dealing with more complicated custom objects. Let's say you define an object Classroom
with several different member variables, including ints, bools, and lists. If you went to print a Classroom
object to console, what would it look like? You would override the toString()
method to define what you would want a Classroom
object's string to look like. (E.g. maybe you would want it to print the list of students in the classroom, or the classroom's room number or teacher's name, etc.)

- 3,928
- 3
- 37
- 68
toString is called whenever you need to convert an object to a String, e.g. when you want to print it.

- 1,019
- 7
- 11