next up previous
Next: Exercises Up: Unit 03 Previous: The toString() method

Use of toString() in print() and println()

The predefined class PrintStream contains variants of the methods print() and println(), which we have used till now, that have a formal parameter of type reference to Object instead of String. These two methods invoke on the parameter of type Object the method toString(), and then print the resulting string using the printing method that we have already seen for String. In practice, this allows us to avoid the explicit use of toString() in the argument of print() and println().

Example:

public class TestToString2 {
  public static void main(String[] args) {
    Person p = new Person("Pippo", "Topolinia");
    System.out.println(p);
    // this is equivalent to System.out.println(p.toString());
  }
}


next up previous
Next: Exercises Up: Unit 03 Previous: The toString() method