Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java (>=7 version) does not support to run program without main method? [closed]

Tags:

java

static

jvm

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

like image 980
PKS Avatar asked Jan 07 '23 13:01

PKS


2 Answers

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.

like image 121
Peter Lawrey Avatar answered Jan 22 '23 04:01

Peter Lawrey


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.

like image 41
ΦXocę 웃 Пepeúpa ツ Avatar answered Jan 22 '23 02:01

ΦXocę 웃 Пepeúpa ツ