Print null in java

When executing the following line:

System.out.println(null); 

the result is null printed on the console.

Why is this happening?

+4
source share
5 answers

Speaking from OpenJDK 1.6.0_22 sources:

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(); } 
+13
source

Because 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 zero, then the string "null" is printed.

+6
source

In fact, at least in java version 1.8.0 System.out.println(null); Do not print null . You will receive an error message:

the reference to println is ambiguous, both the println (char []) method in PrintStream and the println (String) method in the PrintStream mapping. enter image description here

You will need to do the following: System.out.println((String)null); See coderanch post here . I suppose you could do System.out.println(null+""); to achieve the same.

+4
source

As a result, it calls String.valueOf(Object) , which looks like this:

 public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); } 
+3
source

When I look at javadoc for PrintStream I observe (I quote here)

Print

public void print (String s)

Print the line. If the argument is zero, then the string "null" is equal to printed. Otherwise, string characters are converted to bytes according to the default character encoding of the platform, and these bytes are written in exactly the same way as the write (int) method. Parameters: s - String to print

Hope this should answer your question.

+2
source

All Articles