Wednesday 3 April 2013

Can we run the java program without main block?


Yes, we can run java program without defining the main method. This can be easily understand by the below java program.

Example:

public class withoutMainMethod

{

    static
    {
        System.out.println("This is a java program without main method");
        System.exit(1);
    }
   
}

Output of the above program is:
[This is a java program without main method]

And, if we don’t write System.exit() in static block then
Output of the above program is:
 [This is a java program without main method]
Exception in thread “main” Java.lang.NoSuchMethodError: main

As we all know that the execution of java program starts from the main method of the public class so we can’t imagine our program running without main method but in java there is one thing which will always be executed before main method and that thing is static. In java we have three type of static:
1.       Static class
2.       Static Variable
3.       Static Block
 Static variable and static block will always be executed first in any java program so in the above example, we took static block to illustrate that java program can run without main method.
In above example we created a class withoutMainMethod and defined a static block in it with having the output message without defining the main method. When we run the above program it will always give the output message written in the static block. It means that the static block will execute.

Note:- We have also written System.exit() method in static block to terminate the execution in the static block after giving the output message if we don’t write System.exit() then the program will always give an exception stating “Exception in thread “main” Java.lang.NoSuchMethodError: main”. This program may not run in ID(Netbean, Eclipse) but when we run this java program from command prompt it will always show the output message.

No comments:

Post a Comment