Is it possible to write a java program without main method? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Is it possible to write a java program without main method?

26th Oct 2021, 5:52 AM
Atul
Atul - avatar
6 Answers
+ 4
U Can't write program with main but their are many ways to do it u can write the code in static block and and use exit statement at the end becz statement block executing before the main . Other way u can extends your class with application class it will also work fine but better to write main function it will be more readable the things how are implementing
26th Oct 2021, 8:09 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 2
No, It Will Give You An Error...
26th Oct 2021, 6:06 AM
Sancho Godinho
Sancho Godinho - avatar
+ 2
Up to JDK 1.6, we can execute java program with static block From JDK 1.7 onwards even though the program contains a static block it is mandatory to mention the main method
26th Oct 2021, 1:30 PM
sree harsha
sree harsha - avatar
0
you can write it, compile it, but from java 7 jvm can't execute it. Static block can execute if main() existed, however then main() can be empty.
26th Oct 2021, 6:08 AM
zemiak
0
Actually yes. Well, if the project isn't a console application of course, which is the program method main. We are talking about different Projects right now, but if you refer only as the console application, then no, you can't without the main method. For example, in web applications there is no method main. Here an example: - https://stackoverflow.com/questions/20900098/why-dont-i-see-any-main-method-in-this-java-dynamic-web-project
26th Oct 2021, 7:53 AM
Sudo-Ale
Sudo-Ale - avatar
0
static block not work with System.exit() public class A { static { System.out.println("done"); System.exit(0); }} also if you run your code by framework or container your java launcher has main method, so somewhere main() always is
26th Oct 2021, 8:54 AM
zemiak