Static block is not executing in JDK 7, “Main method not found”, but works in JDK 1.5

前端 未结 9 2085
我寻月下人不归
我寻月下人不归 2021-01-07 20:19

I have written a simple class with one static block

class Hello
{

  static {
           System.out.println(\"Hello\");
       System.exit(0);
     }
}


        
相关标签:
9条回答
  • 2021-01-07 21:13

    The program doesn't execute because from JDK 1.7 oracle has put the restriction on static block and static variable calling method if your program doesn't have main method with proper signature but static block and method will always be execute first.As memory management of static variables are done at the time of class loading.

    0 讨论(0)
  • 2021-01-07 21:18

    You need to probably put public static void main(String[] args){ } method in your class for JDK7. In JDK7, main method's presence is checked before the static block and if it doesn't find one you get the exception.

    0 讨论(0)
  • 2021-01-07 21:19

    Java 7 looks for a main method before loading the class. This is a behavior change from previous java versions and hence your static block is not executing. In previous versions, the behavior was that JRE used to look for main method post loading the class and after executing the static blocks.

    0 讨论(0)
提交回复
热议问题