Friday, February 17, 2012

Running javaProgram without main() not possible in JDK1.7 latest Version

Running Java Program without main() has become an old story now.
So far we used to write the program like this
StaticDemo.java
public class StaticDemo
{
   static
    { 
        System.out.println("Hello");
        System.out.exit(0); 
     }
}
And then >javac *.java
>java StaticDemo

It compiles and runs successfully,printing Hello

This works well in JDK1.7 old versions(build 1.7.0-ea-b19)

But From jdk 1.7(build1.7.0-ea-b85),It gives run time Exception

Error: Main method not found in class StaticDemo, please define the main method
   public static void main(String[] args)


The latest version while writing this article was build  jdk 1.7(build 1.7.0_03-b05),which also doesnot allow running java program without main();

So the Concept is:
When we say
java StaticDemo
Compiler understands that we are trying to execute the program,so before executing the static block,it first checks whether main() is there or not.If not,throws Exception

No comments:

Post a Comment