Sunday, 16 April 2017

Why java main method is public static void main(String []args)?

Pubilc - The main method must be public so it can be found by the JVM when the class is loaded.

Static - Since it is static it can be directly invoked via the class. Similarly, we use staticsometime for user defined methods so that we need not to make objects.

Void - void indicates that the main() method being declared does not return a value.

String []args - String is the class which can able to store collection of  characters and strings. []args refers the array of object which can store command line arguments when the program is executed with command line arguments.

For example,

java MyProgram one two

Then args contains: [ "one", "two" ]

public static void main(String [] args) {
    String one = args[0]; //=="one"
    String two = args[1]; //=="two"
}

No comments:

Post a Comment