Java toString () Method

If you want to represent any object as a string, toString() method comes into existence. Implementing toString method in java is done by overriding the Object’s toString method. The java toString

Advantage of the 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.

The java toString() method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String representation of the Object. Below is a program showing the use of the Object Default toString java method.

Problem without toString() method

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, "Mithilesh", "Noida");
		Student s2 = new Student(102, "Rahul", "Delhi");

		System.out.println(s1);// compiler writes here s1.toString()
		System.out.println(s2);// compiler writes here s2.toString()
	}
}

Example of Java toString() method

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 String toString() {// overriding the toString() method
		return rollno + " " + name + " " + city;
	}

	public static void main(String args[]) {
		Student s1 = new Student(101, "Mithilesh", "Noida");
		Student s2 = new Student(102, "Rahul", "Delhi");

		System.out.println(s1);// compiler writes here s1.toString()
		System.out.println(s2);// compiler writes here s2.toString()
	}
}