Tuesday, 14 April 2015

Public static void main(string args[]) Explanation

Public :The main method must be declared as public because it means it is visible to all(spatially for JVM) and can be called from anywhere.

Static: is a special [optional] keyword that indicates that this method can be called without creating an instance of this class means no need to create an object to invoke the main method and It is used with main().

void: is the return type of this method, indicating that this method doesn't return anything.

main: is the name of a function. main() is special because it is the start of the program.

String[] args : is a single parameter for the method. String[] is the type of the parameter, indicating an array of Strings. args is the name of the parameter. Parameters must be named.

Note:String[] args and String args[] Both of them are absolutely the same and both create an array (reserves a place in memory)with no size and name args.
Example:                         
public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

}

Steps to execute the java program.
Step1: Save the above code in java file
Helloworld.java
 public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

}

Step2: Compiling a Java program : Open the command prompt or (terminal for linux) just execute below command
javac HelloWorld.java

Step3: Executing a Java program: Once you compile your program, you can run it. This is the exciting part, where the computer follows your instructions. To run the HelloWorld program, type the following at the terminal:

java HelloWorld