Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

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)?

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top