println(String s) vs println(Object o)
It seems to me that PrintStream.print(Object x)
and PrintStream.println(Object x)
are identical to PrintStream.print(String x)
and PrintStream.println(String x)
.
Is there any obvious reason for having both? Are they different in any way? API-docs-readability? Efficiency?
(With autoboxing, I suspect that even the print-methods taking primitives as arguments are redundant... however these methods predate the autoboxing feature so that's explain开发者_StackOverflow社区able.)
They don't do the same thing:
print(Object x)
calls String.valueOf(x)
, which returns:
(obj == null) ? "null" : obj.toString();
So we have an additional toString()
method.
The result is the same, because String.toString()
returns this
. But for the ease of use of the API, the user should not be forced to understand these details.
PrintStream.print(Object x)
prints string generated by
String.valueOf(Object)
But
PrintStream.print(String x)
prints the character sequence, if null
it will print null
精彩评论