Tuesday - 18 March, 2025 +91

Java Program Without Main Method


In this post we are going to discuss whether is it possible to write a Java program without main method. Many people thinks that it is possible via applets but I am talking about standalone Java program.

And the answer is Yes. It is possible to write a Java program with out main method. Here is the sampe code.


class NB
{
   static
       {
            System.out.println("Welcome to sainadhreddy.in");
            System.exit(0);
        }
}

Actually the funda is in Java program execution starts from static block. So I has placed my code in the static block { …. }. After the execution of the static block JVM searches for the main method. If the main method is absent it will throw main method not found exception. Hence I has terminated my program by calling the exit method so that no error messages are displayed.

The above program will not work from Java SE 7 onwards. In Jdk1.7 the above program will compile fine. But when you try to run it will give the followiing error.
Error: Main method not found in class NB, please define main method as: 
public static void main(String[] args)


It seems that Java 7 specifications does not allow to execute a Java program without main method.

So the answer you have to tell is up to Java SE 6 it is possible to execute a Java program without main method. But from Java SE 7 onwards it is not possible.


Share the info with your friends if you like it. Happy programming…

0 comments:

Post a Comment