Will a static block execute without the main method?
abstract class test extends javafx.application.Application {
static {
System.out.println(“hello”);
System.exit(0);
}
}
Compile using : javac -source 1.6 test.java
Run using : java test
This will even work with JDK 1.8. ð
Static blocks execute when a class is initialized. Normally, the main
class will cause initialization of the bootstrap class, but there are other ways to bootstrap a program, for example via a VM's native embedding API.
Invoking the static main
method of a class causes its initialization, but so do many other things:
- creating an instance of that class,
- calling any other static method,
- reading a static field (that is not final or has type other than a primitive type or String).
For more detail see the JLS chapter 12.4
The below shows this in action
public class Foo {
static { System.out.println("Foo initialized"); }
public static void main(String... argv) {
Initialized.callingThisCausesClassInitialization();
}
static class Initialized {
static { System.out.println("Initialized initialized"); }
static void callingThisCausesClassInitialization() {}
}
static class NotInitialized {
static { System.out.println("NotInitialized initialized"); }
static void callingThisCausesClassInitialization() {}
}
}
Running foo will print
Foo initialized
Initialized initialized
It will not print
NotInitialized initialized
because nothing is done during the execution of that program that causes its initialization.
It looks like your class has that behavior because it is never used, like NotInitialized
above.
If you put a System.exit(0)
at the end of the static
-block, it will run with no errors in Java 6 and below (without a valid main
!). This is because the static
block is executed before a valid main
method is searched for, so if you exit the program at the end of the static block, you will receive no errors.
However, this behavior was changed in Java 7; now you must include an explicit main
, even if it might never be reached.
In Java 7, the answer to the question is false, but in Java 6 and below the answer is indeed true.
public class Test {
static {
System.out.println("Hello World");
System.exit(0);
}
}
Java 6:
Hello World
Java 7:
Error: Main method not found in class Test, please define the main method as: public static void main(String[] args)
In java 8 you can not run a program without explicitly write a main method. From this angle the answer false. Static block is not executed without main method.Below is a piece of code which shows the order of initializaion .(Static block==>main==>initialization block==>constructor)
public class StaticBlock {
static{
System.out.println("in static block");
}
{
System.out.println("in initialization block");
}
public StaticBlock(){
System.out.println("in const");
}
public static void main(String[] args) {
System.out.println("in main method");
StaticBlock block=new StaticBlock();
}
in static block
in main method
in initialization block
in const