1

I have just started learning java and I have a general question. In case I have multiple main functions in different classes in my code, which main will execute first? Can I use one main()? In which class should it be placed? Thank you in advance

Souraya
  • 53
  • 10
  • It'll always be the one you pick. (just a small remark: there are no functions in Java, but methods). Depending on how you run your code (command line, .jar, IDE) the way of configuring which one is called is different, but it remains up to you. The computer is in fact not really a "smart" object. All it can do, is exactly what you (or somebody else) tells (and teaches) him to do. – Stultuske Apr 02 '15 at 11:22
  • The Answer is http://stackoverflow.com/questions/3759315/can-we-overload-the-main-method-in-java – underwater ranged weapon Apr 02 '15 at 11:24
  • this is not duplicate – Andrii Plotnikov Jun 06 '17 at 14:35

3 Answers3

1

The only main that will execute is the one in the class you're executing. Either by specifying the class on the command line with java foo.bar.Class or the one specified in the manifest file when running with java -jar myjar.jar. If you have a jar containing multiple classes having main methods, you can run any of them with java -cp myjar.jar foo.bar.ClassName.

Running via an IDE depends on the IDE.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

Java will only call the main method of the class passed to JVM. If you want to execute MyClass's Main() function, you will need to run the following command in the directory of the compiled class files: java MyClass

You only need the main function in the class you're passing through the JVM as startup class.

Initializing an object instance of a class will not call the Main() method without explicitly calling the function.

ilian
  • 129
  • 1
  • 1
  • 7
0

which main will execute first?

main with string array arguments main(String[] a) when you are running like java ClassName(jvm call) and if you are calling with other class you can call any main() depends on parameter supplied

Note: you can overload main function but you cant have function with same name and parameter.

Can I use one main()? In which class should it be placed?

main() is the entry point used by JVM to your classes so if your running classes individually like java ClassName where JVM only requires main() so the main() is needed for each class

singhakash
  • 7,891
  • 6
  • 31
  • 65