+ 1

Can we create a program in java without main()..??

8th Jun 2017, 9:37 AM
Vignesh R
Vignesh R - avatar
2 Answers
+ 7
Yes, we can run the Java program without main method.  We can use the SIB(Static initialization block).whenever, class is loaded SIB executes.  We can have 'n' number of SIB's that will be executed from top to bottom. SIB is going directly into the Stack memory. Example:  Public class {  static      {            System.out.println("class without main method");           //System.exit(0);       } } Output:  class without main method  Nosuch method. error --------> to remove this one we have to use System.exit(0); statement. It is going to terminate the program there it self. It won't look for the main method then.  
8th Jun 2017, 9:47 AM
The Search
The Search - avatar
+ 18
Now we can't. This can only be done till java 6. Here's how we could've done it : public class Drunk{ static{ System.out.println("Without main()"); System.exit(0); } } If you want, you can try it out by setting up the jdk with Java 6. Code playground has version 8 so it won't work here.
8th Jun 2017, 9:44 AM
Dev
Dev - avatar