The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


The toString Method

There are two object methods that are common to many object types: toString and equals. toString converts the object to some reasonable string representation that can be printed. equals is used to compare objects.

When you print an object using print or println, Java checks to see whether you have provided an object method named toString, and if so it invokes it. If not, it invokes a default version of toString that produces the output described in Section 9.6.

Here is what toString might look like for the Complex class:

  public String toString () {
    return real + " + " + imag + "i";
  }

The return type for toString is String, naturally, and it takes no parameters. You can invoke toString in the usual way:

    Complex x = new Complex (1.0, 2.0);
    String s = x.toString ();

or you can invoke it indirectly through print:

    System.out.println (x);

Whenever you pass an object to print or println, Java invokes the toString method on that object and prints the result. In this case, the output is 1.0 + 2.0i.

This version of toString does not look good if the imaginary part is negative. As an exercise, fix it.



Last Update: 2011-01-24