Can we run java program without main method?

Can we run java program without main method?

We all know it well that main() method in java is entry point to all java programs. Thus it becomes an interesting question for interviewer - 'Is it possible to run java program without main method?'


Yes, we can run or execute a java program without main method.


By using static block, we can execute a code without main method. But static block is supported by systems with java version less than Java SE1.7.

package StaticPack; 

//static block example by 
public class StaticBlock { 

   //static block
   static { 
     System.out.println("For java version less than 1.7"); 
     System.out.println("static block will get execued before main() method"); 

    //main method
    public static void main(String[] args) { 
       System.out.println("main executed after static block"); 


For java version less than 1.7
static block will get execued before main() method
main executed after static block


In the above code, from the output, we can conclude that static block is executed before the main method.

Thus by using static block, we can let our java program execute before main() method. But only in system that supports version less than Java SE 1.7


If you are asked this question in interview then always remember to mention the version or else interviewer will definitely ask it as a follow-up question.


Java Interview Questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by

About the Author
Sonu Pandit
Technology geek, loves to write and share knowledge with the world. Having 10+ years of IT experience. B.Tech in Computer Science & Engineering
Page Views :    Published Date : Aug 22,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!