Monday, June 6, 2011

Executing a Java Program without main() method.

Did you get any doubt why main() is a must to run any java program ?? Can we run without main() method in java ?? , the answer is yes. WE CAN run the JAVA program without MAIN() method.
  1. Create a Class with any class name.
  2. Write a Static block and write the statements to execute.
  3. At the end of the static block give System.exit(0), to avoid the exception in thread main() no main() method found.
  4. Now save the file with the [class_name].java.
  5. Finally compile and run.
EXAMPLE :
The Demonstration of above steps is show bellow
  1. class nomain //step1
  2. {
  3. static//step 2
  4. {
  5. System.out.println("This is in Static method");//step3
  6. System.exit(0);//step 4
  7. }
  8. /* public static void main(String []args)
  9. {
  10. System.out.println("This won't execute");
  11. }*/
  12. }



running and compiling
javac nomain.java
java nomain.java
output :
This is in Static method




2 comments:

  1. Somewhere I read that this won't work in JDK 7. Is that true?
    Anyways, will include this to my reference to main method where I collect notes for various concepts of Java
    Thanks.
    Main method working in java

    ReplyDelete