Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Is it possible to run program without main method?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 337
    Comment on it

    Can we execute a program without using main?

    Answer is yes, we can run a program without using main with the help of static block. Lets see about static block first.

    Static Block:

    It is block which can be used to give initial values to the static data members of the class. When a class is being loaded, then first this block gets executed and after this the main method is executed.

    Lets see with the help of an example:

    class TestStatic{  
      static{System.out.println("Inside static block");}  
      public static void main(String args[]){  
       System.out.println("Inside main");  

    So we will get the output as:

    Inside static block

    Inside main

    Now you can use this block to run the program without main by using System.exit() but there is one limitation.

    This is only possible  for versions less than JDK 1.7 and will not support for JDK 1.7 and above.

    Lets see an example for this:

    class StaticWithoutMain{  
      System.out.println("Hello, This is static block");  

    So , we will get the output as:

    Hello, This is static block

    If you run in JDK 1.7 and above you will get the error message like this:

    Error: Main method not found in class StaticWithoutMain, please define the main method as:
    public static void main(String[] args)


 0 Comment(s)

Sign In

Sign up using

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: