Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is java main method called?

Tags:

java

main

  1. I have a class(1) having some constructors(arg and no args). In another class(2) an object of Class 1 is created using new constructor(). So will main method get called in this case?

  2. Ideally when is main method called in any class?

like image 707
iAmSavy Avatar asked May 08 '12 06:05

iAmSavy


People also ask

How Java main method is called?

As we know, the main() method for any Java application as the Java Run time environment calls the main() method first. So it is obvious that we don't need to call the main() method by ourselves as it is already called when the program starts.

Is main method called First in Java?

main is a static method, the entry point for the program, and is called once (unless you explicitly call it), when the program starts, not for each object initialization.

Who calls the main method in Java program?

Jvm starts main thread to call main method.

Does Java automatically run Main?

All Java programs must have an entry point, which is always the main() method. Whenever the program is called, it automatically executes the main() method first.


2 Answers

Any class can have a main method. For example, both your Class(1) and Class(2) classes can have a main method, but only one will be called once when your program is ran.

When you run the program, for example, java class1 - you tell Java that you wish to START the program using the main method of Class(1). This can be confusing, as you'd think Java would execute each and every main method it finds, but that's not the case. Once Java has found and ran the main method in the class you specified, it will ignore all future main() methods it may find as it's already executed a main method for your program.

You can think of main() as the door that leads into your program, once in, the computer won't try to come in again, it's already in the program! I hope this helps you a bit.

like image 167
Ewald Avatar answered Oct 05 '22 14:10

Ewald


main is a static method, the entry point for the program, and is called once (unless you explicitly call it), when the program starts, not for each object initialization.

like image 23
MByD Avatar answered Oct 05 '22 12:10

MByD