-1

Let's consider following code:

public static void main(String[] args) {
    Integer i = null;
    Object o = null;

    System.out.println(i);
    System.out.println(o);

    System.out.println(i.toString());
    System.out.println(o.toString());
}

That's quite obvious that last two prints will cause NullPointerException. One can't call method on null object.
The question is why first two prints work? Aren't they calling toString() as well?

Kacper
  • 4,798
  • 2
  • 19
  • 34

3 Answers3

4

No they aren't.

System.out is a PrintStream and it calls String.valueOf(x) on the argument (as described in the the Javadoc).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
  • I've added a link to the relevant Javadoc, feel free to roll back if you don't want this. – Andy Turner Nov 14 '16 at 13:44
  • I've closed as dup to the relevant existing question. And still wondering why nobody else had that idea ... – GhostCat Nov 14 '16 at 13:45
  • 1
    Sometimes it's more fun to answer trivial questions than try to find duplicates. – Kayaman Nov 14 '16 at 13:46
  • @Kayaman I know, and its not like that I never did that ... probably I am just envious that Jarred "I will downvote any question and any answer that even shows the slightest close distance to some DUP" wasn't around. As he seems to always be around when I do *accidentally* answer DUPs. – GhostCat Nov 14 '16 at 13:48
2

No, they are not.

There is a null pointer check inside of System.out.println (*).

Something along the lines of

println(x == null ? "null" : x.toString());

(*) the argument goes through String#valueOf, which takes care of this.

Thilo
  • 257,207
  • 101
  • 511
  • 656
1

Look at the implementation of print(String s):

public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
}

If the object happens to be null, it simply writes "null". Taken from java.io.PrintStream:GrepCode

QBrute
  • 4,405
  • 6
  • 34
  • 40
  • Haha, there's even two null-checks actually performed for the OP's call - first, `PrintStream.println()` does the check mentioned in my answer, then calls `PrinsStream.print()` which checks for null again as per yours. – Jiri Tousek Nov 14 '16 at 13:45
  • This code path isn't called in OP's code: `s` is `"null"`, not `null`, because `String.valueOf(s)` is never null. – Andy Turner Nov 14 '16 at 13:48
  • @AndyTurner ah that's right. I stepped to the lowest point in the calling hierarchy where the null check is done and overlooked the `String.valueOf(s)` before. – QBrute Nov 14 '16 at 13:51