Print Welcome without main method java class How will you do this

Print Welcome without main method java class How will you do this

Answer: I have seen many times people say yes it’s possible to print message without the main method using static block and gave reason for program sequence is as follows:

  • JVM loads class
  • Executes static blocks
  • Looks for main method and invokes it

Above is absolutely correct if you have main method in your class but if you don’t provide main method and try to run program with static method shown below you will get exception:

package com.javahonk;

public class MainMethodTest {    

    static {
	System.out.println("Welcome");
    }   

}

 

Try by yourself you will see below exception:

Error: Main method not found in class com.javahonk.MainMethodTest, please define the main method as:
   public static void main(String[] args)

 

Leave a Reply

Your email address will not be published. Required fields are marked *