Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

The toString() method is used to return a string representation of an object. By default, the toString() method returns a string that consists of the class name, an "@" symbol, and the object's hash code in hexadecimal format. All objects have a toString method that returns the class name and a hash of the object's memory address. We can override the default method with our own to print out more useful information.

However, it is common practice to override the toString() method to provide a more meaningful string representation of an object. To override the toString() method, you can define the method in your class and return a string that includes the values of the object's fields.

public class Person {
  private String name;
  private int age;

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  @Override
  public String toString() {
    return "Person{name='" + name + "', age=" + age + "}";
  }
}

In this example, the toString() method of the Person class has been overridden to return a string that includes the name and age fields of the person object.

You can call the toString() method on an object by using the object's name followed by the method name, like this:

Person person = new Person("John Doe", 30);
String str = person.toString();
System.out.println(str); // output: Person{name='John Doe', age=30}

You can also call the toString() method implicitly by passing an object to a method that expects a string, like this:

Person person = new Person("John Doe", 30);
System.out.println(person); // output: Person{name='John Doe', age=30}

  • No labels