Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Method toString() | Classes
Java Extended
course content

Contenido del Curso

Java Extended

Java Extended

1. Deep Java Structure
2. Methods
3. String Advanced
4. Classes
5. Classes Advanced

bookMethod toString()

How to easier print an object?

To display all the data of an object using the System.out.println(object); command in Java, there is a method called toString();.

toString()

The toString method in Java is a built-in method that belongs to the Object class. It is used to return a string representation of an object. By default, when we call toString on an object, it returns a string that contains the class name followed by the hashcode of the object. Let's look at the example:

java

Main

copy
1234567891011121314151617181920
package com.example; class Person { String name; int age; String gender; public Person(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } } public class Main { public static void main(String[] args) { Person bob = new Person("Bob", 20, "male"); System.out.println(bob); } }

HashCode

A hashcode, in simple terms, is a unique identifier for an object that is stored in memory. We can also see the hash code of an object by calling the hashCode() method on it, for example:

java

Main

copy
123456789101112131415161718192021
package com.example; class Person { String name; int age; String gender; public Person(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } } public class Main { public static void main(String[] args) { Person bob = new Person("Bob", 20, "male"); int code = bob.hashCode(); System.out.println(code); } }

In that case, the question arises: how can we get something more specific instead of the hash code of an object? For such cases, we can override the toString() method.

Inheritance and method overriding are extensive topics that we will study in a separate course. For now, we will use method overriding only for the toString() method.

How to use toString()

To override a method, we need to use the following syntax:

java

Main

copy
1234
@Override public String toString() { // block of code }

Note that we use the annotation @Override before this method. With this annotation, the compiler recognizes that we are overriding this method. Next, we specify the syntax public String toString(), indicating which exact method we are overriding.

In the body of this method, we will define how our object should be represented as a string. Let's override the method for the Person class:

java

Person

copy
12345678910111213141516171819
class Person { String name; int age; String gender; public Person(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } @Override public String toString() { return "Class Person;" + System.lineSeparator() + "name = " + name + ";" + System.lineSeparator() + "age = " + age + ";" + System.lineSeparator() + "gender = " + gender + "."; } }

The System.lineSeparator() command is used to create a new line. We have defined how our object should appear by concatenating strings with their values. Therefore, when we try to print an object of the Person class, we will see detailed information about each field. Let's output an object using the main method and see how it looks:

java

Main

copy
12345678910111213141516171819202122232425262728
package com.example; public class Main { public static void main(String[] args) { Person bob = new Person("Bob", 20, "male"); System.out.println(bob); } } class Person { String name; int age; String gender; public Person(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } @Override public String toString() { return "Class Person;" + System.lineSeparator() + "name = " + name + ";" + System.lineSeparator() + "age = " + age + ";" + System.lineSeparator() + "gender = " + gender + "."; } }

Note

Note that we don't explicitly call the toString() method; it is automatically invoked when we pass an object to System.out.println().

We have obtained information about the class to which the object bob belongs and details about all its fields. Thus, we can override and define the toString() method to display the desired information when printing an object. Let's create another object of this class using the constructor to see and reinforce how the toString() method transforms the object:

java

Main

copy
123456789101112131415161718192021222324252627282930
package com.example; public class Main { public static void main(String[] args) { Person bob = new Person("Bob", 20, "male"); System.out.println(bob); Person alice = new Person("Alice", 17, "female"); System.out.println(alice); } } class Person { String name; int age; String gender; public Person(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } @Override public String toString() { return "Class Person;" + System.lineSeparator() + "name = " + name + ";" + System.lineSeparator() + "age = " + age + ";" + System.lineSeparator() + "gender = " + gender + "." + System.lineSeparator(); } }

We can see that the new object alice is displayed in the console using the same template.

Conclusion

By using the toString() method, we have greatly simplified the process of displaying object information on the screen, allowing us to save space in the main method.

Note

You can also customize the toString() method to display the desired information. Keep in mind that this method should be implemented in the class of the object you want to display on the screen.

1. Why do we need the ``toString()`` method?
2. Which annotation should be used above the ``toString()`` method?
Why do we need the ``toString()`` method?

Why do we need the toString() method?

Selecciona la respuesta correcta

Which annotation should be used above the ``toString()`` method?

Which annotation should be used above the toString() method?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 8
some-alt