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?
Ideally when is main method called in any class?
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.
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.
Jvm starts main thread to call main method.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With