java - order of execution of static method -


public class sample {      public void method()     {         system.out.println("normal hai");        }     public static void method1()     {         system.out.println("static hai");     }     public static void main(string[] args) {         sample s = null;         s.method1();         s.method();      } } 

and output is:

exception in thread "main" java.lang.nullpointerexception         @ com.csvfile.sample.main(sample.java:22)  static hai 

why has order changed? should output:

static hai exception in thread "main" java.lang.nullpointerexception     @ com.csvfile.sample1.main(sample.java:22) 

the issue have exception printed system.err while code prints system.out.

so, without badly named class (pascalcase please) can do:

public static void main(string[] args) throws exception {     final system system = null;     system.out.println("odd");     system.out.println(system.tostring()); } 

and output is:

exception in thread "main" java.lang.nullpointerexception odd     @ com.boris.testbench.app.main(app.java:14)     @ sun.reflect.nativemethodaccessorimpl.invoke0(native method)     @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62)     @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43)     @ java.lang.reflect.method.invoke(method.java:497)     @ com.intellij.rt.execution.application.appmain.main(appmain.java:140) 

so they're interleaved. i.e. order of output undefined there 2 output streams being printed console.

changing code to:

public static void main(string[] args) throws exception {     final system system = null;     system.err.println("odd");     system.err.println(system.tostring()); } 

produces desired result.

you catch exception , print system.out achieve 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 know this, should never call static method on instance of class. should call static method on class itself. in example, should do:

public static void main(string[] args) {     sample1 s = new sample1();     s=null;     sample1.method1();     s.method();  } 

Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -