Java toString () Method
If you want to represent any object as a string, the toString () method appears.
The toString () method returns a string representation of the object.
If you print any object, the java compiler internally calls the toString () method of the object. Thus, overriding the toString () method returns the desired result, it may be the state of the object, etc. Depends on your implementation.
Advantage of the Java toString () Method
Overriding the toString () method of the Object class, we can return the values of the object, so we do not need to write a lot of code.
Exit without toString () method
class Student{ int id; String name; String address; Student(int id, String name, String address){ this.id=id; this.name=name; this.address=address; } public static void main(String args[]){ Student s1=new Student(100,"Joe","success"); Student s2=new Student(50,"Jeff","fail"); System.out.println(s1);
You can see in the example above # 1. printing s1 and s2 prints the Hashcode values for the objects, but I want to print the values of these objects. Because the java compiler internally calls the toString () method, overriding this method returns the specified values. Let me understand this with the example below:
Example#2 Output with overriding toString() method class Student{ int id; String name; String address; Student(int id, String name, String address){ this.id=id; this.name=name; this.address=address; }
Note that toString () is mainly related to the concept of polymorphism in Java. In Eclipse, try clicking on the toString () button and right-clicking on it. Then click “Open Declaration” and see where Superclass toString () came from.
Linux Le Jul 02 '15 at 1:31 on 2015-07-02 01:31
source share