Wednesday, January 22, 2014

How to execute a java code without using MAIN method?

How to  execute a java code without using MAIN method?

At Compile time ,compiler will not look for any main method but  at runtime, JVM will look for a main method .
At Runtime, JVM performs three main task  :

1> Class loading è where class will be loaded from file location into JVM.

2> Byte code verification where byte code verifier will verify the byte code

3> Runtime or Execution where JVM will look for main method in the java class and it will run that main method .

JVM looks  for main method in  the 3rd phase but what if we can execute the code before that phase…
Question : How we can run any code before the 3rd phase  ?
Ans:
We can run  a code  after the class loaded  using static  initializer or static blocks.
STATIC Initializer (Static block ):
Static block runs after the class is loaded into JVM but before the  main method.

Here is the sample code:

Class Test
{
          Static
{
                  System.out.println(“Hello…program without main function.”);
                  System.exit(0);
}
}
Output :
E:\> javac Test.java
E:\> java Test
Hello…program without main function.
E:\>

As you can see there is no main method in the code , but still its working because static block runs before the main method.  
But yes , at the end JVM will look for main method and throws the error to avoid that use System.exit(0)
Note:
è System.exit(0) :  Terminates the currently running Java Virtual Machine so that the code will not get into the third phase if we skip System.exit(0)  then JVM will look for main method and it will throw "java.lang.NoSuchMethodError: main Exception in thread main "and we don’t want that.


è This will not work in JAVA 7 because Java 7 looks for a main method before loading the class. This is a behavior change from previous java versions and hence static block will not execute. In previous versions, the behavior was that JRE used to look for main method post loading the class and after executing the static blocks.

No comments:

Post a Comment