Unexpected runtime error in plain 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));

      

Expected Result:

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

      

The result was very close to this, but out of order:

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

      

It got the last value true

, but got it after the start of the exception. And while at some level I assume this is a stupid question (because the code made it look like it should), I can't help but wonder why there was an error before the previous command had finished completely. What happens on the program execution stack to make this happen?

+3


source to share


1 answer


There are two streams in the console that your program can use for output. There "standard error" and "standard error". You are explicitly posting to "standard"; and your error message goes to "standard error".

Now, although both of these streams end at the console, "standard out" has a small buffer. Therefore, the text going to "standard error" might go to the console text AHEAD OF, which was "standard" at first.



You can experiment with this by mixing calls with System.out.print

and System.err.print

.

There is good information about this page .

+2


source







All Articles