How to override toString() method in Java
The toString() method returns the string representation of an object. It is widely used for debugging, printing objects’ contents in logs, etc. This post will discuss how to override the toString() method in Java.
The object class already contains the toString() method, which returns a string that “textually represents” the object. The default implementation of the Object.toString() method returns a string consisting of the class name, '@' character, followed by the unsigned hexadecimal representation of the hash code of the object. i.e,
|
1 2 3 |
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } |
Since all Java objects inherit from java.lang.Object, you need to override the toString() method to get the desired string representation. Otherwise, the above default implementation of the toString() method will be invoked when you try to print an object. For instance,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Country { private String name; private String continent; private long population; public Country(String name, String continent, long population) { this.name = name; this.continent = continent; this.population = population; } } public class Main { public static void main(String[] args) { Country country = new Country("United States", "North America", 331449281); System.out.println(country); } } |
Output:
Country@5197848c
To print the contents of an object, you must have your class override the toString() method. This can be done in several ways:
1. Using String Concatenation Operator
You can use the String concatenation operator + to append member variables in a class clearly and concisely. Although the String concatenation using the + operator is not recommended in Java but can be done without a loop since the Java compiler implicitly creates an intermediate StringBuilder object.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Country { private String name; private String continent; private long population; public Country(String name, String continent, long population) { this.name = name; this.continent = continent; this.population = population; } @Override public String toString() { return "Country{" + "name='" + name + '\'' + ", continent='" + continent + '\'' + ", population=" + population + '}'; } } public class Main { public static void main(String[] args) { Country country = new Country("United States", "North America", 331449281); System.out.println(country); } } |
Output:
Country{name='United States', continent='North America', population=331449281}
2. Using 'StringJoiner'
In Java 8 and above, we can use the StringJoiner class, which takes a delimiter and construct a sequence of values separated by the delimiter.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.StringJoiner; class Country { private String name; private String continent; private long population; public Country(String name, String continent, long population) { this.name = name; this.continent = continent; this.population = population; } @Override public String toString() { return new StringJoiner(", ", Country.class.getSimpleName() + "[", "]") .add("name='" + name + "'") .add("continent='" + continent + "'") .add("population=" + population) .toString(); } } public class Main { public static void main(String[] args) { Country country = new Country("United States", "North America", 331449281); System.out.println(country); } } |
Output:
Country[name='United States', continent='North America', population=331449281]
3. Using Guava’s 'MoreObjects.ToStringHelper()'
Guava’s MoreObjects class provides several helper functions that operate on any Java Object. To implement Object.toString() method, you can create an instance of MoreObjects.ToStringHelper, and call add(name, value) method for each field. The add(name, value) method adds the name-value pair to the output in name=value format.
If you just need to add an unnamed value to the output, call the addValue(value) method. Also, you can ignore properties with null values using the omitNullValues() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import com.google.common.base.MoreObjects; class Country { private String name; private String continent; private long population; public Country(String name, String continent, long population) { this.name = name; this.continent = continent; this.population = population; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("continent", continent) .add("population", population) .toString(); } } public class Main { public static void main(String[] args) { Country country = new Country("United States", "North America", 331449281); System.out.println(country); } } |
Output:
Country{name=United States, continent=North America, population=331449281}
4. Using Apache Commons 'ToStringBuilder' class
Similar to Guava MoreObjects class, Apache Commons Lang library provides the ToStringBuilder class to assists in implementing Object.toString() methods. To use this class, write code as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import org.apache.commons.lang3.builder.ToStringBuilder; class Country { private String name; private String continent; private long population; public Country(String name, String continent, long population) { this.name = name; this.continent = continent; this.population = population; } @Override public String toString() { return new ToStringBuilder(this) .append("name", name) .append("continent", continent) .append("population", population) .toString(); } } public class Main { public static void main(String[] args) { Country country = new Country("United States", "North America", 331449281); System.out.println(country); } } |
Output:
Country@69d0a921[name=United States,continent=North America,population=331449281]
Alternatively, you can directly invoke the reflectionToString() method that uses reflection to generate a toString for the specified object. Note that this method might fail under a security manager, since it uses AccessibleObject.setAccessible to change the visibility of the private fields in the class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import org.apache.commons.lang3.builder.ToStringBuilder; class Country { private String name; private String continent; private long population; public Country(String name, String continent, long population) { this.name = name; this.continent = continent; this.population = population; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } public class Main { public static void main(String[] args) { Country country = new Country("United States", "North America", 331449281); System.out.println(country.toString()); } } |
Output:
Country@67424e82[continent=North America,name=United States,population=331449281]
Note that almost all IDEs (Eclipse, IntelliJ IDEA, etc.) offer support for auto-generating the toString() method, based on the member variables in the class. It is recommended to use the respective IDE features to generate the toString() method instead of writing it yourself. For instance, in IntelliJ IDEA, you can simply right-click on the source code, choose the Generate menu, and select the toString option. Alternatively, just press Alt+Insert and select the toString option.
IntelliJ IDEA further offers flexibility to choose between different toString templates, like StringBuilder, ToStringBuilder (Apache commons-lang 3), Objects.toStringHelper (Guava), MoreObjects.toStringHelper (Guava 18+), StringJoiner (JDK 1.8), String concat (+), etc.
That’s all about overriding the toString() method in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)