Can anybody explain to me the concept of the toString()
method, defined in the Object
class? How is it used, and what is its purpose?
It may optionally have uses within the context of an application but far more often it is used for debugging purposes. For example, when you hit a breakpoint in an IDE, it's far easier to read a meaningful toString()
of objects than it is to inspect their members.
There is no set requirement for what a toString()
method should do. By convention, most often it will tell you the name of the class and the value of pertinent data members. More often than not, toString()
methods are auto-generated in IDEs.
Relying on particular output from a toString()
method or parsing it within a program is a bad idea. Whatever you do, don't go down that route.