Technical discussions about .NET and J2SE Concepts

Java Program without main() method

Hi Friends….Greetings to Everyone….

Can we able to write and execute a java program without writing a main() method? Any guesses….?

Yes friends…Its possible with the help of static block in java.

We all knew that, the heart and soul of the program execution is main() in java. But its true only in the case when you are not having static block in your java program.

Because static block of statements are getting executed at the first instant by the Java Interpreter.

For Example – Program with both static block and main():

class StaticBlockDemo
{
//Static Block Definition
static
{
System.out.println(“Statements inside Static Block……”);
System.out.println(“Statements inside Static Block……”);
}//End of static block

public static void main(String[] args)
{
System.out.println(“You are in Main Function – Starting Point of Program Execution”);
}
}//End of class

When you are executing the above program, you can find that static block of statements getting executed first and then the main() method starts its execution.

Java Program: Without writing main()

import java.lang.*;  //Optional
class StaticBlockWithoutMainDemo
{
//Static Block Definition
static
{
System.out.println(“Statements inside Static Block……”);
System.out.println(“Statements inside Static Block……”);
System.exit(0);
}//End of static block
}//End of class

Save the above program with StaticBlockWithoutMainDemo.java in your local drive.Then compile and run the program in a normal way.

Thank You Friends!!!

 

Advertisements

3 responses

  1. Vengatesh NE

    Thank You. Please post some other interview questions which is related to Java Concepts. I have experienced the same question in my previous interview panel.

    June 24, 2013 at 5:49 am

    • Thank You Mr. Vengatesh NE. I will do post some other interview questions further…..

      June 24, 2013 at 6:19 am

  2. Pingback: Limitations of static block in Java? | Jeyakumar Kandasamy's Technical Guide

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s