Skip to content
Advertisement

Unexpected runtime error placement in simple Java code

I generated the following code for a multiple choice question on an exam:

    String a = "";
    String b = null;
    String c = null;
    String d = "";
    String e = new String("");
    System.out.print((b==c) +" ");
    System.out.print((a==d) +" ");
    System.out.print((d==e) +" ");
    System.out.print((d.equals(e)) +" ");
    System.out.println(c.equals(b));

The output I expected was:

true true false true Exception in thread "main" java.lang.NullPointerException

The output I received was very close to that, but out of order:

true true false Exception in thread "main" true java.lang.NullPointerException

It did get that last true value, but it got it after the exception began. And while, on some level I suppose this is a silly question (because the code did sort-of what it was supposed to), I can’t help but wonder why the error came in before the prior command fully terminated. What is going on in the program execution stack to make this happen?

Advertisement

Answer

There are two streams to the console, that your program can use for output. There’s “standard out” and “standard error”. You’re explicitly putting messages on “standard out”; and your exception message goes to “standard error”.

Now, although both of these streams end up at the console, “standard out” has a small buffer. Therefore, text going to “standard error” can arrive at the console AHEAD OF text that went to “standard out” first.

You can experiment with this by mixing up calls to System.out.print and System.err.print.

There’s some good information on this page.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement