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.
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.
No, System. out. println() does not call toString().
Your toString() method is actually being called by the println method.
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.
Your examples call two different methods in PrintStream. Both call toString()
at most once.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With