In Java, the toString()
method is a method of the Object
class that returns a string representation of the object. The toString()
method is used to convert an object to a string so that it can be displayed or printed.
By default, the toString()
method returns a string that contains the name of the object's class and a unique identifier for the object, in the format "classname@hashcode"
. For example, if you have an object of the Person
class, the default toString()
method might return a string like "Person@234567"
.
Here's an example of how you can use the toString()
method to convert an object to a string:
Person p = new Person("John", "Doe"); String str = p.toString();
In this example, the p
variable is an object of the Person
class, and the toString()
method is called on the p
object to convert it to a string. The resulting string is stored in the str
variable.
You can override the toString()
method in your own classes to customize the string representation of your objects. For example, you might want to include the object's field values or other relevant information in the string representation.
Here's an example of how you can override the toString()
method in the Person
class to customize the string representation of Person
objects:
public class Person { private String firstName; private String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return firstName + " " + lastName; } }
In this example, the toString()
method is overridden to return a string that contains the firstName
and lastName
fields of the Person
object, separated by a space.
The toString()
method is a useful way to convert an object to a string for display or printing purposes.