views:

70

answers:

5

I've had a big problem in some library code, which I've pinned down to a single statement:

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

Ok, the code doesn't actually look like that, but it certainly calls println with a null argument. Doing this causes my whole applicaio to throw an unexpected NullPointerException.

In general, should println throw this exception under that circumstance, or is this non-standard behavior due to a poor implementation of the out instance?

+4  A: 

The JVM of sun prints simply "null". This is the specified behavior of PrintStream.print(String) when given a null argument.

tangens
+1  A: 

That above shouldn't throw an exception. Are you sure you don't have something like:

System.out.println(a.b);

where a is null ?

Alternatively, perhaps your System.out has been set to null (not many people realise that you can set the out/err streams)?

Brian Agnew
No, I ran that code on its own, on my platform, and it threw a `NullPointerException`.
Eric
A: 

When I try that line on standard desktop Java (Java SE 6 update 20 on Mac OS X), it does not throw a NullPointerException, it just prints null.

I think that throwing a NullPointerException is a bug in this case.

Jesper
A: 

I just tried running this on sun's jdk 6 and it worked just fine. It printed null as expected.

Jay Askren
+2  A: 

Ok, found the error, in my platform's implementation of PrintStream.print. I guess I'll follow it up with the developers.

public void print(String s) {
    // WHERE IS THE NULL CHECK??!
    for(int i=0;i<s.length();i++) {
        write(s.charAt(i));
    }
}

Thanks for confirming that this is indeed non-standard behaviour.

Eric