Home 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 :

No comments:

Post a Comment