Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

println(String s) vs println(Object o)

Tags:

java

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 explainable.)

like image 525
aioobe Avatar asked Feb 15 '26 05:02

aioobe


2 Answers

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.

like image 110
Bozho Avatar answered Feb 16 '26 19:02

Bozho


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

like image 37
Dheeraj Joshi Avatar answered Feb 16 '26 17:02

Dheeraj Joshi