Tuesday, May 18, 2010

Java program that runs without Main method

Most of you heard about this popular question.this post is for those who did not know about this.
While Learning Java in Computer Centre,my Mam asked me this question. I replied, immediately “Mam, Applets run without main method,is this is answer?” ;) . It is also a right answer I think..But it is not the answer what she expected. She asked me to write a program again, without main method,, after some time I gave her the answer,[ I read related article already ]. I wrote the following program.
class NMM //No main method
{
static
{
System.out.println(“This is the Java Program That Runs Without Main Method”);
System.exit(0);
}
}
Reason is, before the main block getting executed, the static initializations gets executed. So You might ask , why this System.exit(0) line. This is to terminate the program, when it throws exception because of the class not having main method.

No comments:

Post a Comment