Wednesday, February 11, 2015
How to Execute Your Java Program Without main Method
Have you ever thought about executing your java programwithout 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.
- 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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.