-4

I recently started learning Java and the first doubt I encountered is main is declared static in java so that JVM don't have to initialize the class for accessing main. But my question is why JVM avoid initializing the class which has main? What cost does it incur if we declare main as non-static?

vivs0766
  • 33
  • 2
  • 6
  • It's probably important to clarify that Java draws a distinction between *initializing* and *instantiating* a class. The class gets initialized exactly once, sometime after it is loaded by a class loader and before any methods of the class are called; the initializer assigns values to static variables, for example. The class gets instantiated when a new instance is created and its instance initializer (that is, constructor) runs. – Daniel Pryden Sep 19 '18 at 15:45

4 Answers4

4

The compiler will treat as an instance method, i.e. you won't be able to execute it directly with java YourClass.

But my question is why JVM avoid initializing the class which has main?

Because there's no need of initializing the class, since it cannot be an entry point to the application. At Runtime, JVM will check for the presence of a public static void main(String[] args) method and if there is one, then it will initialize the class (i.e. execute all it's static blocks, initialize it's static variables and so on). However, if the class is considered as in invalid for being an entry point to the application, the operation will break.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • *"But my question is why JVM avoid initializing the class which has main? What cost does it incur if we declare main as non-static?"* ;) – MadProgrammer Jun 15 '15 at 05:45
  • "Even if a main() method is present, Java will throw an exception if it isn’t static. A nonstatic main() method might as well be invisible from the point of view of the JVM" - OCA Oracle Certified Associate Java SE 8 – basit9 Dec 04 '22 at 13:10
0

The keyword static allows main() to be called without having to instantiate a particular instance of that class. This is neccessary because main() is called by JVM before any objects are created.

How do you execute if you don't have entry point?

DDan
  • 8,068
  • 5
  • 33
  • 52
0

Bootstrap class loader searches for main function in the class file, if main function is not declared as static, it will trough an error because declaring function as static allows it to be called without instantiating that class file where the main function is.

0

As with the help of static keyword any variable, method or statement block can be called without creating any object (or instant) of the class in which it is declared. That is why main() is declared static so that it can be called without creating any object. If it is not declared static, and if more than one class is there then how JVM will know to which class is instantiated to call main method.