Printing null in java [duplicate]
On execution of following line :
System.out.println(null);
the result comes out to be null printed on console.
Why does that happen?
Telling from the sources of OpenJDK 1.6.0_22:
PrintStream:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
String:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Actually, at least in java version 1.8.0, System.out.println(null);
should not print null
. You would get an error saying something like:
reference to println is ambiguous, both method println(char[]) in PrintStream and method println(String) in PrintStream match.
You would have to cast as follows: System.out.println((String)null);
See coderanch post here.
I suppose you could also do System.out.println(null+"");
to accomplish same.
Because that's exactly what the Javadocs say will happen?
http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#print(java.lang.String)
Prints a string. If the argument is null then the string "null" is printed.
It's eventually calling String.valueOf(Object)
which looks like:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
When I look at the javadoc for PrintStream I observe (I am quoting here)
public void print(String s)
Print a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method. Parameters: s - The String to be printed
Hopefully that should answer your question..
精彩评论