Showing posts with label Print Object in Java. Show all posts
Showing posts with label Print Object in Java. Show all posts

Friday, June 17, 2016

Print Object in Java

To print objects in Java, we can use toString() method.
toString() method belongs to object class.

class Student{
String name;
int id;
String city;

Student(String name, int id, String city){
this.name = name;
this.id = id;
this.city = city;
}
public String toString(){
return " Name: "+name + " id: "+id + " city: "+city;
}

public static void main(String[] args){
Student S1 = new Student("Dj", 111, "Irving");
Student S2 = new Student("Rabi", 222, "Dallas");
System.out.println(S1);
System.out.println(S2);
}
}

Now, the output will be:
               Name: Dj id: 111 city: Irving
Name: Rabi id: 222 city: Dallas

If we don't use the toString() method and directly print the object, we get some garbage values that we cannot understand.