Wednesday 29 March 2017

Can a java program be executed without having main()

We all have heard many times that main method is the entry point for any java program.

So whenever a program is executed, jvm starts searching for main method with
public static void main(String args[]){}
Signature.

And then whatever follows within main method starts getting executed.

But what if we omit the main method in a java program and still want the program to get executed.
There is still the way, if you are using version lesser than JDK 1.7

Solution is use static block

Try this example on your editor and execute it.

class noMainMethod{

    static{

      System.out.print("getting executed without main");

   }

}

So the solution is write your code in static block as shown above.

Note: Remeber this won't work if you are on JDK 1.7 or above version.

All you will get as output will be something like this

Output:

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


You may also like to read:


--------------------------------------------------*-----------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java Head First
Click on the image link below to get it now.





5 comments:

  1. To avoid the error, the SIB body should end with System.exit(0). This statement ensures that the compiler will not search for main() after execution of the SIB.

    ReplyDelete
  2. SIBs & IIBs and also constructors can be used to do so..

    ReplyDelete
  3. Thank you Devina & Ashutosh for adding points to discussion on the given topic.
    For novice programmar, I would like to inform them here,
    SIB is static initialization block
    IIB is instance initialization block

    I have already explained SIB in above post. Will be adding link to IIB on the post shortly.
    Thank you readers <--> Java Radar

    ReplyDelete
  4. Why this static block doesn't work for JDK 1.7 or above?

    ReplyDelete
  5. Why this static block execution without main method doesn't work in JDK 1.7 or above ?

    ReplyDelete

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.