toString() method within System.out.println() a double call?

Andrew Campbell picture Andrew Campbell · May 15, 2013 · Viewed 18.6k times · Source

A professor of mine once said that the following code should never be done:

System.out.println(object.toString());

He said (and I believe cited "Effective Java") it causes a double call. Since the print statement calls the toString method of an object, it would be less efficient to have the toString method called twice. The preferred method would be to just use:

System.out.println(object);

Obviously this way looks better in code and would save time. I will always do it like this no matter what, but my question is "Is this actually more EFFICIENT?". In looking through the PrintStream documentation, the print method has been overloaded to take a String as the parameter (which would be the case if the toString method were called first). I am not seeing where that version of the print method calls the toString method of the inputted parameter and I don't believe it would make sense for it to do that.

Also, sorry if this is a duplicate. I couldn't find any topics on it.

Answer

Andy Thomas picture Andy Thomas · May 15, 2013

Your examples call two different methods in PrintStream. Both call toString() at most once.

  • The first method calls println(String x), which does not call x.toString() itself.
  • The second method calls println( Object x ), which leads to a call of x.toString() if x is not null.

However, there is a potential advantage to using System.out.println(object). If object is null, this prints "null". The other statement throws a NullPointerException.