Home Core Java Overview Maven Tutorials

Saturday, 14 January 2017

toString() method in Java with example

For Video Tutorial : Move on Youtube Channel

Note : Select the playlist as per your need & move with number sequence

toString in Java

For Video : CLICK HERE

If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation 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. depends on your implementation.

toString Example in Java

public class Student
int RollNo;
String Name;
String City;
Student(int Rollno, String Name, String City)
this.RollNo = RollNo;
this.Name = Name;
this.City = City;
public static void main(String args[])
Student s1 = new Student(101, "Chandan", "Noida");
System.out.println(s1); //compiler writes here s1.toString()
output : Student@15db9742
Second Example :

toString Example in Java

public class Emp2
public String name;
public int age;
public String city;
public Emp2(String name, int age, String city)
{ = name;
this.age = age; = city;
public String toString() //overriding the toString method
return name+ "" +age+ "" +city;
public static void main(String[] args)
Emp2 ob = new Emp2("chandan", 26, "noida");
Emp2 obj = new Emp2("amit", 10, "village");
System.out.println(ob);//compiler writes here ob.toString()
output :

1 comment:

  1. Hm...The code is doesn't work, compiled it several times but without result somehow. The explanation is good, but there I found more detailed lesson about parseint java I read it on the recommendation of my mentor to study Java and HTML for one of the famous IT-office. In this tutorial, I have found a program that detects what elements that causes an issue. It only works for lists but has helped me to debug my own method.