Printing hello without using main method:
We can use static block to print something without using main method as static block executes as soon as the class is loaded. To ignore exception "System.exit(0);" is used which terminates the program at the end of the block .
class WithoutMain
{
static
{
System.out.println("java program without main method");
System.exit(0);
}
}
Output:
java program without main method
If we will not exit the above program with System.exit(0); then it will give "main method not found" exception.
But it was possible only upto Java6 , it will not work in Java7 and above version . JDK7 and above version will give following error:
Error: Main method not found in class WithoutMain, please define the main method as:
public static void main(String[] args)
0 Comment(s)