How to Execute Your Java Program Without main() Method?

Have you ever thought about executing your java program
without main() method? If you write a program without main() and compile it
then it will compile successfully. But as you execute the program it will show
an error that Main method not found in the class. JVM verify the code before
its execution. JVM checks for main() method and if not found it will show
error.
How to Execute Your Java Program Without main() Method?
There is a way to execute your java program without using
main(). This can be done using static block. JVM has four phases as I have
discussed in one of my article about Java Virtual Machine Architecture and Structure.
  • Load Code
  • Verify Code
  • Execute Code
  • Provide Runtime Environment
Static block executed at the loading of code. In below
example we get output and then error is shown because the code is executed at
loading of code and after that JVM verifies the code and show error.
class demo
{
                static
                {
                                System.out.println(“Static
Block”);
                }             
}
Note:  This method will work till Java 6. Java 7 and
newer versions doesn’t allow this because JVM checks presence of main method
before initializing the class.

If you have any other
such trick then you can share it by commenting below.

2 thoughts on “How to Execute Your Java Program Without main() Method?”

  1. abstract class test extends javafx.application.Application
    {
    static
    {
    System.out.println(“hello”);
    System.exit(0);
    }
    }

    Compile using : javac -source 1.6 test.java
    run using : java test

    This will even work with jdk 1.8.. 🙂

Leave a Comment

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