In Java, Up to Java 6 it was possible to do this using the Static Initialization Block. For solve the problem to a execute java program without having main method.
For example we have writing the following code using static block:
public class CheckWithoutMain{
static{ System.out.println("static block is Executed");
System.exit(0);
}
}
Output: (In JDK 6)
The System.exit (0); is used to the program exit before the JVM is looking for the
main method, otherwise error will be thrown:
Exception in thread “main” java.lang.NoSuchMethodError:main
In Java 7 & above, however, this does not work anymore, even though it compiles,
the following error will appear when you try to execute it:
The program compiled successfully, but main class was not found. Main class
would contains method: public static void main (String [] args).
Output: (In JDK 8)
So, we have only execute a java program without having main method up to valid Java versions 6.
0 Comments