开发者

Printing null in java [duplicate]

This question already has answers here: Why does null reference pr开发者_JAVA技巧int as "null" (3 answers) Closed 6 years ago.

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.

Printing null in java [duplicate]

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)

print

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜