Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 699
Andrew Campbell Avatar asked May 15 '13 16:05

Andrew Campbell


People also ask

What is the use of toString () method in Java?

Java - toString() Method The method is used to get a String object representing the value of the Number Object. If the method takes a primitive data type as an argument, then the String object representing the primitive data type value is returned.

Does system out Println automatically call toString?

No, System. out. println() does not call toString().

How do we call toString () method?

Your toString() method is actually being called by the println method.

In which class toString () method is defined?

Object class is the parent class in Java. It contains the toString method. The toString method is used to return a string representation of an object.


2 Answers

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.

like image 102
Andy Thomas Avatar answered Nov 15 '22 16:11

Andy Thomas


No, it is not more efficient -- precisely because of the overload that you mentioned. Moreover, a call of toString on a String is extremely quick, so even without an overload the difference would not be measurable.

However, your professor is right about not making the call like System.out.println(object.toString());, but the reason is different: since the call is unnecessary, the readers of your code may get confused.

like image 21
Sergey Kalinichenko Avatar answered Nov 15 '22 17:11

Sergey Kalinichenko