Feb 20, 2012

Java Program without a Main Function

Writing a simple program in JAVA to print "Hello world " is not a big task for you, if you are a programmer in JAVA. But i m going to teach you how to write a program without a main function.
  You may ask me , every program starts with Main Function and how come its possible to do without a main method. Java provides you to use static initialization block to achieve this..

Ex:

public class Sample{
 static{
System.out.println("Hello World !");
 
}


By running this class, you will get an error message stating that "java.lang.NoSuchMethodError: main
Exception in thread "main" " . To avoid this, add System.exit(0); at the end of static initialization block.

public class Sample{

static{
System.out.println("Hello World !");
  System.exit(0);
}
}

No comments:

Post a Comment

Post a Comment

Note: Only a member of this blog may post a comment.