How to override toString() Method

As known Object class is base class of all classes in Java. Object class provides some methods, which are useful for each and every Java class. Among the methods provided by Object class toString() is one of the important method.

Below is declaration of toString() method
public String toString();

Below is an example showing how to override toString()

//Overriding toString() method
class A2{
	int i,j;

	public A2(int i,int j)
		this.i = i;
		this.j = j;
//toString() actually is being implemented in Object class
	public String toString()
		return " "+i+" "+j;


public class OverrideToString {
public static void main(String args[])
	A2 oa = new A2(10,20);
	System.out.println("Check Value:"+oa.toString());

Check Value: 10 20

Output of above program, on commenting toString() implementation in A1 class:
Check Value:A2@1f33675

You may also like to read: Difference between String and String Builder