Java - toString() method

What is toString() method?

toString method returns the String Representation of an Object.

You can reimplement the toString() method of the Object class in your class.

Syntax

The signature of toString method is as follows:


public String toString()

Default Implementation

The Object class provides a default implementation of the toString() method.

It returns a string in the following format:

<fully qualified class name>@<hash code of object in hexadecimal>

Demo

class Point {
  private int x;
  private int y;

  public Point(int x, int y) {
    this.x = x;/*from  www .j  a v  a 2 s .c o m*/
    this.y = y;
  }

}

public class Main {
  public static void main(String[] args) {
    Point pt1 = new Point(10, 10);

    System.out.println(pt1);
  }
}

Result

Here is an re-implementation

public String toString() {
    return "Here is a string";
}

Demo

class Test {
  /* Re implement the toString() method of the Object class */
  public String toString() {
    return "Here is a string";
  }//from  ww w . ja v  a  2 s  . com
}

public class Main {
  public static void main(String[] args) {
    Test t = new Test();
    System.out.println(t);
  }
}

Result

Related Topics