The issue you have is that the Exception
is printed to System.err
while your code prints to System.out
.
So, without a badly named class (PascalCase
please) we can do:
public static void main(String[] args) throws Exception {
final System system = null;
system.out.println("Odd");
System.out.println(system.toString());
}
And the output I get is:
Exception in thread "main" java.lang.NullPointerException
Odd
at com.boris.testbench.App.main(App.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
So they're actually interleaved. i.e. the order of the output is undefined as there are two output streams being printed to the console.
Changing the code to:
public static void main(String[] args) throws Exception {
final System system = null;
system.err.println("Odd");
System.err.println(system.toString());
}
Produces the desired result.
You could also catch the exception and print it to System.out
to achieve the same effect:
public static void main(String[] args) throws Exception {
final System system = null;
system.out.println("Odd");
try {
System.out.println(system.toString());
} catch (RuntimeException ex) {
ex.printStackTrace(System.out);
}
}
P.S. I'm sure you know this, but you should never call a static
method on an instance of the class
. You should always call the static
method on the class
itself. So in your example, you should always do:
public static void main(String[] args) {
sample1 s = new sample1();
s=null;
sample1.method1();
s.method();
}