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.
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.
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.
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.
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”);
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.
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.
such trick then you can share it by commenting below.
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.. 🙂
Is there any other way to run a program without main in java 11 version.