Why main() method is always static in Java?In Java, the main() method plays a vital role in program execution. The main() method is the first method that encounters first during execution. So, it is an entry point of a program. We cannot modify the syntax of the main() method. The only thing which we can change is the name of the String array argument. The syntax of the main() method is as follows: Let's divide the syntax of the main() method into several parts and understand each one of them: 1) publicIt is not so complicated to understand. It is an access modifier of the main() method. We create main() method with public access specifier to execute it by any program. So, it is required to define main() method public and if we define the main() method as non-public, it will throw the following error: TestMain.java Output: 2) staticThe static is a keyword which we use in the main() method to define it as static. There is no object of the class available at the time of starting java runtime, and because of that, we have to define the main() method as static. By doing that, JVM can load the class into the main memory and call the main() method. So, if we define main() method as non-static method, JVM would not be able to call it and throws the following error: TestMain.java Output: 3) voidAs we know that, each method provides some return type such as String, Boolean, Integer etc. The Java main() method doesn't return anything, and its return type is void. The main() method doesn't return anything to make things simple. The program will be terminated after executing the main() method, and returning anything from the main() method is worthless because JVM will be done nothing for the returned object. If we return something from the main() method, it will throw the following error: TestMain.java Output: 4) main()It is the name of the main() method. The name of the method is static and we cannot change it. If we try to change the name of the method(), it will throw the following error: TestMain.java Output: 5) String[] args or String args[]The Java main() method takes a single argument of type String array as a parameter also referred to as a command-line argument. Let's take an example and understand how the command-line argument works. TestMain.java Output: Reasons for defining main() method as staticWe cannot call a method without creating an instance of its class, and we already told you before that at the time of starting JVM, there is no object of a class. We create the main() method as static so that JVM can load the class into the main memory.
Next TopicBellman-Ford Algorithm Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India