Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to run a program without a main metod in JAVA?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 186
    Comment on it

    First of all see the following program::

    public class Hello{
        static{
            System.out.print("Hello! Running Java program without main method.")
            System.exit(0);
        }
    }
    

    The output of above program will be::

    Hello! Running Java program without main method.
    

    As you can see, its possible to run a program in Java without using a main method simply by using Static Initialization Block . The code inside static block is executed only once. But this code will only work upto JAVA 6 not in the later version.

    When Java compiler compile the code as soon as class is loaded statement inside Static block are executed and message is printed on the screen.

    System.exit(0);
    

    This line lets the program exit and will prevent the JVM for looking the main method after the static block is executed, otherwise following error will be printed on the screen::

    Exception in thread "main" java.lang.NoSuchMethodError: main
    

    NOTE: In Java 7 & or above version this code will not work. Though the compiler will compile the code,the following error will occur when you will try to run the program:

    The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: