class WithoutMain {
static
{
System.out.println("Without main class!!!");
System.exit(0);
}
}
when I am trying to to run above code in java version greater than 7 i am getting below error. The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).
can someone please guide me why Java does not support to run program without main after java7
AFAIK this change was specific to Java 7. In Java 8 you can do this. You can't do this in Java 7 as it looks for the method without loading the class first which fails. In any case, it has been changed back in Java 8.
public class Main {
static {
System.out.println("Without main class!!! with " + System.getProperty("java.version"));
System.exit(0);
}
}
prints
Without main class!!! with 1.8.0_66
Note: this will kill the whole program. If you want the program to keep running without a main you can do this
public class Main {
static {
// do something which starts threads
System.out.println("Without main class!!! with " + System.getProperty("java.version"));
if (true)
throw new ThreadDeath();
}
}
This will prevent the error message, but leave background threads running provided there is a non-daemon thread.
the static section
static
{
System.out.println("Without main class!!!");
System.exit(0);
}
will be executed every time the JVM load the class in memory, but if you want to start a java application, you will need a main method, because that it the start point of every java application, if you dont define it, then the JVM will have no idea where to start.
you can expand your code and do something like:
class WithoutMain {
static
{
System.out.println("Static section!!");
}
public static void main(String[] args){
System.out.println("Main class!!!");
}
}
and the output will be the static section first and then the code you define in the main method.
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