Explanation of public static void main in Java
In java , we have encountered a most common syntax many times which is something like this-
We all have written this code when we are first introduced with java. But , most of us are unaware about what this codes says. What is the use of public static void main() and why it is always written like this , no matter how much the length of code. Its format is still the same.
Lets try to understand this one by one -
public - This public keyword is an access modifier. Now , what access modifier is ? It is used to help to know who can access the method or variable. There are 4 types of access modifiers - public , protected, private and default. This main method is declared as public so that we JVM can invoke it outside of the class and evryone can access it to provide output. If it is changed to any other modifier then JVM would not be able to access it and main method will not invoked by it causing error that - main class not found.
static- It is also a keyword which helps main method to directly invoked by JVM without instantiating the class and save the unnecessary wastage of memory by declaring the object of class and then call the main method. So , if main method is not declared as static it will give error itself that- make main method as static.
void- It is the return type of the main method . As main method terminates , java program terminates too. so , there is nothing to do with the return value of the main method. JVM can't do anything with the return value from main method unlike in c . So , it is declared as void - that doesn't return anything. It we change the return type other than void , lets say int , it will return error - that main method not found.
main- It is not a keyword. main is the name of the method and an identifier. But if we change the name of the main method , we get error as - main method not found in the class . So , it needs to be main and no other name is entertained by JVM for running the class.
String[] args- It stores Java command line arguments. This args name is not fixed and can be anything like - a, b, c etc. When we run java program, we can give multiple inputs in string in command line itself and can use in code by retrieving it from string[] args.
Comments
Post a Comment