1

This is an interview question I was asked. We all know that execution of a Java program begins from the main method with the following signature:

public static void main(String[] arg)

Is there a way to change the starting point of execution of the Java program, to another method, say by tweaking any JVM configuration parameters?

  • you can add static block so it becomes starting point. – virendrao Mar 23 '15 at 05:51
  • Well an `Applet` would work as well, pretty basic way too. – Obicere Mar 23 '15 at 05:52
  • I don't think that's a good idea or necessary at all, it makes people confusing, and there could even be security issue. And you should ask the interview guy why they need to do that. – Eric Mar 23 '15 at 06:12

3 Answers3

4

No. Regardless of what the application does under the covers, or how things may get fiddled about, your program must contain a method that is declared public static void main(String[] args) (or some vararg declaration of args).

This is outlined in the JLS, section 12:

The Java Virtual Machine starts up by loading a specified class and then invoking the method main in this specified class.

Should main not exist, a runtime error ensues - specifically, NoSuchMethodError (and it will complain about not finding main).

Makoto
  • 104,088
  • 27
  • 192
  • 230
1

Is there a way to change the starting point of execution of the Java program, to another method, say by tweaking any JVM configuration parameters?

The answer is no . you cant .

When normal JVM starts to run a class it looks for main method in the class.that is the way jvm is designed.

You could also add in your answer that .. there are other execution models for a java program. for example applet,servlet etc

applet will run in browser which supports jvm without a main method. servlet will run in servlet container without main method.

What ever you add in static block is executed before main ... but still the class will not run without main. Hence you could theoretically change starting point of java program by adding a static block but the program execution will fail if no main in class.

If you want to go ahead and show off then you could say that since main is not a keyword .. we can change jvm code to recognize another method name instead of main ..but for that we change jvm code .. cannot pass as parameter

Raj
  • 1,945
  • 20
  • 40
0

It is indeed possible to start an application at any of several methods, all of which are called main by choosing the class that has the main I want. I do this all the time for testing purposes. I would consider this technique as tweaking JVM configuration parameters. Here is what java documentation says about it.

Setting an Application's Entry Point

Marichyasana
  • 2,966
  • 1
  • 19
  • 20