How to execute java program without main() method

Let’s learn how to execute a java program without main() method. Yes, there is a chance of executing Java program without using a main() method.

How to run or execute a java program without main() method

public class Main {
  static {
    
                     System.out.println("hello world");
    
               }

}
//You can even try this way!

You can try this way also!

public class Main {
  public static void main(String[] args) {
  }
  static{
  
    System.out.println("hello world");
    
  }

}

Output:Hello World

Yes, it is possible to run a java program without main() method by using a static block. And the reason that we can execute a program without main() method. Because static block is executed before loading the main() method. There is a limitation to this concept of using static block. It is possible to use static block only if the java JDK version is 5. And on the other latest versions like java 6, 7, it is not possible since we will face an error generated mentioning to add main method to the program. You have to just mention static keyword and then open braces, continue with your code and finally run.




Therefore, for the latest versions, there is no possibility of running java program without main() method. We can use this static method only when the java JDK version is 5 or below.

And in the second example mentioned above, you can run a block of code without main() method by static block which is not in the main() method. This is possible in all versions of JDK and no errors are generated. Hope the examples are clear and explanation is well understood.

Also read:


Leave a Reply

Your email address will not be published. Required fields are marked *