Reputation: 3453
Just wondering if there is ever any reason to call toString()
explicitly on an object to print it?
MyClass obj = new MyClass(); // Assume toString() method is overriden in this class
System.out.println(obj);
System.out.println(obj.toString());
I obviously use the first approach, but one of my co-workers argues that I should put back that obj.toString()
! I feel toString()
is just redundant and not using it actually reduces the chances of NPE
!
Am I missing something or do people have any reason to use toString()
explicitly?
Upvotes: 3
Views: 1690
Reputation: 66886
System.out
is an instance of PrintStream
. If you call println()
you will be calling this code:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
So it's just converting to a String
anyway, although using String.valueOf
. The difference is that String.valueOf(null)
is "null"
and just calls toString()
on the object anyway if it's not null
. But calling toString()
on null
causes a NullPointerException
for sure.
So, use the former. It's simpler and handles null
.
Upvotes: 8
Reputation: 4899
If obj is null the second call will generate an NPE as you pointed out. As @Louis said, provided obj is not null, they're basically the same thing.
I would prefere to override toString() if I want to customize the literal rapresentation of MyClass, calling it WITHOUT the .toString() method to avoid the risk of NPE.
Upvotes: 4
Reputation: 7717
IMHO do not use toString()
explicitly, it could cause null pointer exception
Upvotes: 4