15 years ago
Jump to Forum..
- Boddunan.com Updates
- - Announcements
- - Contests & Rewards
- - Group Discussions
- Discussions
- - General Discussions
- - Improving English Writing Skills
- - Q n A - Find answers to your questions
- - Daily Dose
- - Topics of Interest
- - - Current Affairs & Latest News
- - - Education & Learning
- - - Humor & Jokes
- - - Movies & Entertainment
- Your Vote Counts
- - Feedback
- - Suggestion Box
- Shoutbox
- - Introduce Yourself
- - The Lounge
- - Help
- - Testimonials
Like it on Facebook, Tweet it or share this topic on other bookmarking websites.
15 years ago
You can write a runnable Java program which does not have main method at all. This can be done using the static block of the class.
The reason this works is that static initialization blocks get executed as soon as the class is loaded, even before the main method is called. During run time JVM will search for the main method after exiting from this block. If it does not find the main method, it throws an exception. To avoid the exception System.exit(0); statement is used which terminates the program at the end of the static block itself.
class MainMethodNot
{
static
{
System.out.println("This java program have run without the run method");
System.exit(0);
}
}
The reason this works is that static initialization blocks get executed as soon as the class is loaded, even before the main method is called. During run time JVM will search for the main method after exiting from this block. If it does not find the main method, it throws an exception. To avoid the exception System.exit(0); statement is used which terminates the program at the end of the static block itself.
class MainMethodNot
{
static
{
System.out.println("This java program have run without the run method");
System.exit(0);
}
}
You do not have permissions to reply to this topic.
Related Topics