CH11 – The toString Method

  1. Create a new class named MyToStringDemo and add the following parameters, constructor, and toString method.
public class MyToStringDemo{
  int age;
  String name;

  public MyToStringDemo(int a, String b){
    this.age = a;
    this.name = b;
  }

  public String toString(){
    return "MyToStringDemo age=" + this.age + " name=" + this.name;
  }
}
  1. Add a main method and have it instantiate a MyToStringDemo instance and call its toString method.
public static void main(String[] args){
  MyToStringDemo myDemo = new MyToStringDemo(33,"James Brannan");
  System.out.println(myDemo.toString());
}
  1. Compile and run the program.
$ javac MyToStringDemo.java
$ java MyToStringDemo
MyToStringDemo age=33 name=James Brannan

The complete class should appear as follows.

public class MyToStringDemo{
  int age;
  String name;

  public MyToStringDemo(int a, String b){
    this.age = a;
    this.name = b;
  }

  public String toString(){
    return "MyToStringDemo age=" + this.age + " name=" + this.name;
  }

  public static void main(String[] args){
    MyToStringDemo myDemo = new MyToStringDemo(33,"James Brannan");
    System.out.println(myDemo.toString());
  }
}