Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

I have written a simple class with one static block

class Hello
{

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

When i am running it using jdk1.5, static block is getting executed

C:\apps\Java\jdk1.5.0_21\bin>javac Hello.java

C:\apps\Java\jdk1.5.0_21\bin>
C:\apps\Java\jdk1.5.0_21\bin>
C:\apps\Java\jdk1.5.0_21\bin>
C:\apps\Java\jdk1.5.0_21\bin>java Hello

Hello

But when i am running it using jdk1.7, i am getting following error

C:\Program Files (x86)\Java\jdk1.7.0_02\bin>
C:\Program Files (x86)\Java\jdk1.7.0_02\bin>javac Hello.java

C:\Program Files (x86)\Java\jdk1.7.0_02\bin>java Hello
Error: Main method not found in class Hello, please define the main method as:
    public static void main(String[] args)

Can anyone have any idea about this change of behaviour in JDK 5 and JDK 7?

Thanks in advance!!

like image 313
user2555693 Avatar asked Jul 06 '13 06:07

user2555693


People also ask

Can we execute static block without main method?

Yes, we can execute a java program without a main method by using a static block. Static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by Java ClassLoader, It is also known as a static initialization block.

Can we have static block in main method?

Executing a static block JVM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method.

Why static block is executed before main method?

Because the Java Language Specification mandates that static blocks must be executed first. There can be more than one static block and each of them are executed in the order of their declaration. Static blocks are executed when the class in loaded in memory(JVM).

When a static block is executed in Java?

Static blocks execute when the class is loaded into the memory whereas instance blocks execute only when instance of the class is created. 5. 'this' keyword cannot be used in the static block whereas this keyword can be used in the instance block.


1 Answers

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.

like image 75
Juned Ahsan Avatar answered Sep 24 '22 10:09

Juned Ahsan