Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing object in Java

Tags:

java

tostring

I ran the following code

String str = null;
System.out.println(str);

Output was null.

At first, I thought that the NullPointerException will be thrown as printing the object implicitly calls toString method. So, I was surprised with the output.

Then I contemplated about the output and thought that above String statement actually didn't create any object, only reference is created that doesn't point to any object. So that may be the reason of such output.

Can somebody please let me know if my understanding is correct.

like image 890
Anand Avatar asked Oct 29 '12 18:10

Anand


1 Answers

The print() methods explicitly check for null.

public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
}
like image 166
SLaks Avatar answered Sep 28 '22 03:09

SLaks