Let’s begin with the simplest of program :-
1
Save this file as HelloWorld.java
Commands to compile and execute :-
  • For Compilationjavac filename.java(In our case file name is HelloWorld).
  • For Execution java HelloWorld
Note - From the Command Prompt, navigate to the directory containing your .java files, by typing the cd command.
Now let’s understand the program :-
  • class keyword is used to declare a class in java. HelloWorld is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly brace  {  and the closing curly brace  } .
  • public keyword is an access modifier which represents visibility. It means it is visible to all. So that JVM can execute the method from anywhere.
  • static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create an object to invoke the main method. So it saves memory.
  • void is the return type of the method. It means it doesn't return any value.
  • main represents the starting point of the program. It’s the name configured in the JVM.
  • String args[] is used for command line argument. The main method accepts a single argument: an array of elements of type String.
  • System.out.println is used to print statement, This line outputs the string “Hello, World” followed by a new line on the screen. Output is actually accomplished by the built-in println( ) method. System is a predefined class that provides access to the system, and out is the variable of type output stream that is connected to the console.

Is main method compulsory in Java?

The answer to this question depends on version of java you are using. Prior to JDK 5, main method was not mandatory in a java program.
  • You could write your full code under static block and it ran normally.
  • The static block is first executed as soon as the class is loaded before the main(); method is invoked and therefore before the main() is called. main is usually declared as static method and hence Java doesn’t need an object to call main method.However, From JDK6 main method is mandatory. If your program doesn’t contain main method, then you will get a run-time error “main method not found in the class”. Note that your program will successfully compile in this case, but at run-time, it will throw error.