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!!
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With