0% found this document useful (0 votes)
46 views3 pages

Java toString() Method Explained

Uploaded by

Up ka sher king
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views3 pages

Java toString() Method Explained

Uploaded by

Up ka sher king
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java toString() Method

If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the String representa on of the object.

If you print any object, Java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output, it can be the state of an object etc.
depending on your implementa on.

Advantage of Java toString() method

By overriding the toString() method of the Object class, we can return values of the object, so we
don't need to write much code.

Understanding problem without toString() method

Let's see the simple code that prints reference.

[Link]

1. class Student{

2. int rollno;

3. String name;

4. String city;

5.

6. Student(int rollno, String name, String city){

7. [Link]=rollno;

8. [Link]=name;

9. [Link]=city;

10. }

11.

12. public sta c void main(String args[]){

13. Student s1=new Student(101,"Raj","lucknow");

14. Student s2=new Student(102,"Vijay","ghaziabad");

15.

16. [Link](s1);//compiler writes here [Link]()

17. [Link](s2);//compiler writes here [Link]()

18. }

19. }

Output:
Student@1fee6fc

Student@1eed786

As you can see in the above example, prin ng s1 and s2 prints the hashcode values of the objects but
I want to print the values of these objects. Since Java compiler internally calls toString() method,
overriding this method will return the specified values. Let's understand it with the example given
below:

Example of Java toString() method

Let's see an example of toString() method.

[Link]

1. class Student{

2. int rollno;

3. String name;

4. String city;

5.

6. Student(int rollno, String name, String city){

7. [Link]=rollno;

8. [Link]=name;

9. [Link]=city;

10. }

11.

12. public String toString(){//overriding the toString() method

13. return rollno+" "+name+" "+city;

14. }

15. public sta c void main(String args[]){

16. Student s1=new Student(101,"Raj","lucknow");

17. Student s2=new Student(102,"Vijay","ghaziabad");

18.

19. [Link](s1);//compiler writes here [Link]()

20. [Link](s2);//compiler writes here [Link]()

21. }

22. }

Output:
101 Raj lucknow

102 Vijay ghaziabad

In the above program, Java compiler internally calls toString() method, overriding this method will
return the specified values of s1 and s2 objects of Student class.

You might also like