JavaRush /Java Blog /Random EN /10 Tips for Overriding the toString() Method in Java (Par...
Ku6ep
Level 35

10 Tips for Overriding the toString() Method in Java (Part 2)

Published in the Random EN group

toString examples in Java

We will use the following class to demonstrate our toString example for Netbeans, Eclipse and Apache's ToStringBuilder utility.

/** * Java программа, демонстрирующая How переопределить метод toString() в Java. * Эта Java программа показывает How вы можете использовать IDE типа Netbeans or Eclipse * и открытую библиотеку типа Apache commons ToStringBuilder для * переопределения toString в Java. * @author Javarevisited.blogspot.com */ public class Country { private String name; private String capital; private long population; private Date independenceDay; public Country(String name){ this.name = name; } public String getName(){ return name; } public void setName(String name) {this.name = name;} public String getCapital() {return capital;} public void setCapital(String capital) {this.capital = capital;} public Date getIndependenceDay() {return independenceDay;} public void setIndependenceDay(Date independenceDay) {this.independenceDay = independenceDay;} public long getPopulation() { return population; } public void setPopulation(long population) {this.population = population; } @Override public String toString() { return "Country{" + "capital=" + capital + ", population=" + population + ", independenceDay=" + independenceDay + '}'; } public void setIndependenceDay(String date) { DateFormat format = new SimpleDateFormat("dd/MM/yyyy"); try { this.independenceDay = format.parse(date); } catch (ParseException ex) { Logger.getLogger(Country.class.getName()).log(Level.SEVERE, null, ex); } } public static void main(String args[]) { Country India = new Country("India"); India.setCapital("New Delhi"); India.setIndependenceDay("15/07/1947"); India.setPopulation(1200000000); System.out.println(India); } }

The toString method created by Netbeans IDE


The toString method generated by Netbeans IDE produces the following output for the class defined above:

Country{capital=New Delhi, population=1200000000, independenceDay=Fri Aug 15 00:00:00 VET 1947}

If you look at the above output, you will see that Netbeans is not creating the formatted date for you: instead, it is calling the toString() method of the java.util.Date class

The toString() method created by the Rclise IDE


By default, Eclipse creates the following toString method:

@Override public String toString() { return "Country [name=" + name + ", capital=" + capital + ", population=" + population + ", independenceDay=" + independenceDay + "]"; }

You can generate code for the toString method in Eclipse by clicking on Source --> Generate toString(). It also provides several possibilities, such as choosing the code style, that is, using the concatenation operand or StringBuilder and so on. Below is the output of the toString() method we just created in Eclipse:

Country [name=India, capital=New Delhi, population=1200000000, independenceDay=Tue Jul 15 00:00:00 VET 1947]

Using ToStringBuilder to Override Java's toString() Method

Along with many useful classes such as PropertyUtils , EqualsBuilder or HashCodeBuilder, Apache also provides ToStringBuilder which can generate code to output the toString() method in several different styles. Let's see what the output of the toString method looks like in simple and multi-line style: Simple style:

India,New Delhi,1200000000,Fri Aug 15 00:00:00 VET 1947

Multi-line style:

test.Country@f0eed6[
 name=India
 capital=New Delhi
 population=1200000000
 independenceDay=Fri Aug 15 00:00:00 VET 1947
 ]

NO_FIELD_NAMES_STYLE (style without field names)

test.Country@1d05c81[India,New Delhi,1200000000,Fri Aug 15 00:00:00 VET 1947]

SHORT_PREFIX_STYLE (short prefix style)

Country[name=India,capital=New Delhi,population=1200000000,independenceDay=Fri Aug 15 00:00:00 VET 1947]

ToStringStyle.DEFAULT_STYLE (default style)

test.Country@1d05c81[name=India,capital=New Delhi,population=1200000000,independenceDay=Fri Aug 15 00:00:00 VET 1947]

A similar open source library from Google, Guava also provides a convenient API for generating code for the toString method in Java.

When toString method is called in Java

toString is a fairly specific method and is called from many JavaAPI methods such as println(), printf() , logging, assert statements , IDE debuggers, when printing collections, and when concatenating. If a subclass does not override toString(), then the default implementation defined in the Object class is called. Many developers use logging APIs like Log4J or java.util.Logger to output logs and often miss Object here.

logger.info("Customer not found:" + customer)

and if Customer doesn't override toString and output important information like customerId, customerName, etc. then it will be quite difficult to diagnose the problem. This is why it is always worth overriding toString in Java. Let's take a look at some of the benefits if we do this.

Benefits of overriding the toString method

  1. As discussed above, a properly overridden toString helps with debugging by printing out important information.
  2. If an important object is stored in a collection, then printing the collection will call the toString method of the stored object, which can print out the important information. One classic example of a non-overridden toString method is Array in Java, which prints the result of the default implementation instead of the contents of the array. Although there are several ways to print the contents of an array using Arrays.toString() and the like; but since Array is a Java object, it would be much better if it knew how to print itself, just like collection classes like List or Set .

These are just some of the benefits that you will get by implementing or overriding the toString method in Java , there are many more benefits that you will get and learn for yourself. I hope these tips help you get the most out of your toString implementations. Let us know if you know of any unique ways of working with toString that help you in your Java applications.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION