toString
is a method on every Object
which converts the logical binary representation in memory to a string of characters (String
) in a human readable form.
The default behaviour of toString
as seen in Object.java
is to return:
class name + @ + memory address in hexadecimal
When you create your own classes it's worth to @Override
this method to be able to easily find bugs later on. See SMA's answer on how to do this. Most of the framework's classes have this method already, for example ArrayList
prints: [object 0's toString(), object 1's toString(), object 2's toString()].
When you add an arbitrary object to a String object, like "hello " + empoyee
, toString
is called in the background so it roughly becomes "hello " + employee.toString()
(I say "roughly" because there's more magic involving StringBuilder
, but that's not to be concerned about as a beginner).
It is mostly used for debugging and logging. It's considered bad practice to actually use it in production code and rely on the output of the method in business logic and UI.