Pages

Saturday, December 23, 2006

Can i print in console with out a main method ?

Yes, certainly we can have a Java class without a main method and still have all the work performed.
Consider the Example

public class Beauty {
  static {
          int i = 10;
          System.out.println("The Square of the number is "+"  "+i*i);
         }
}

In the above example the progam would run and also print 100 on the console(with an exception java.lang.NoSuchMethodError Exception).The JVM when it tries to execute the program it would first look for a static intialization block and static variables and then start look for "public static void main(String [])" method signature(which in this case is missing".

0 comments:

Post a Comment