How to use the toString() in Java ?
Omar Ismail
Senior Software Engineer @ Digitinary | Java 8 Certified? | Spring & Spring Boot?????? | AWS? | Microservices ?? | RESTFul Apis & Integrations ?? FinTech ?? | Open Banking ?? | Digital Payments and Transformation??
What is toString()?
A?toString()?is an in-built method in Java that returns the value given to it in?string?format. Hence, any object that this method is applied on, will then be returned as a?string object.
How to use the toString() method
The?toString()?method in Java has two implementations;
What is interesting is that this method can also be?over-ridden?as part of a class to cater to the customized needs of the user. The example below shows how to do this!
In the code above, from?lines 11 to 13?we have simply created a new method within the?Pet?class with the same name as the?toString()?method. On?line 20?when the?toString()?method is called, it is the class version of the method that is invoked. However as seen on?line 22, the method does not change for any other data type!
Thanks To : Edpresso Team From Educative!