Sunday, 6 January 2013

Run a Java Program without the Main Method


STEP 1: Create a class ProgramWithoutMain in any location in your system.

public class ProgramWithoutMain {
 static
{
    String str = "Crazy Blog";   
    System.out.println("I am running without Main method:- "+str);     
    System.exit(0);
   
}
}


STEP 2: Set Java Path and Class path as below.



STEP 3: Now Compile and Run the program as below



Reason Behind

        "Static blocks" declared in any Java class are always called before the main () method.

         Here, as soon as the control reaches static block’s closing brace, it tries to search for main () method. To stop my program from looking for main () method, I would simply call System.exit(0); and terminate the entire Java program.

No comments:

Post a Comment