Ads Sponsored By Google :)

Wednesday 30 January 2013

how can we execute|run a java program without main in java with example


can we run a java program without main method can we run a java program without main can we execute a java program without main method can we execute a java program without main can we execute java program without main method can we execute java class without main can we execute java program without main how can we execute java program without main method how can we execute java program without main how can we execute java program without main with example how can we execute java program without main example how can we execute java program without main method in java  how can we execute java program without main in java how can we execute java program without main in java with example


     Can We Execute a java program without main method?

        Yes it is possible by using static block we can execute the java program. Even though 
    we can execute a java program without main method but we can get an error as without 
   main method execution.
   

     For Example:

      public class Demo{
            static{
                 System.out.println(“this is static block”);
                }
            }
    

  After compilation and running it prints the message this is static block. Then it checks for main  method it not exists, then it prints an error message as no main method…..

   To overcome it printing of no main method we use a method called (i.e:) System.exit(0); 

    Following Code represents Execution of java program without main method 

       public class Demo {
               static {
             System.out.println(“this is static block“);
            System.exit(0);
             }
        }

1 comment:

  1. that is a nice way to execute code when the class is getting loaded. Does this also work in JDK7?
    Points on main method in Java

    ReplyDelete

LinkWithin