Java Tutorial-Java Example

The Example Explained

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

The explanation for the above code is given below:

  • Every line of the code runs in Java must be inside the class file.
  • The class name should always start with the upper case. (Note: Java is case-sensitive: “MyClass” and “myclass” has different meaning).
  • The name of the Java file should be same as the class name.
  • When saving the Java file, save it with the “.java” extension.


The Main Method

The main() method is required in the program from where the execution starts.

public static void main (String[] args)

This is the very important Java method.

public – It has to be “public” so that Java runtime can execute this method. The main method should also should be public.

static – The main method has to be “static” so that JVM can load the class into memory  and call the main method. If the main method is not static, JVM would not be able to call it because there is no object of the class is present.

void – Java main method would not return nothing, that’s why the return type is “void”. Once the Java program is executed, it returns nothing and terminates. Hence, there is no point in returning object from the JVM.

String args[] – Java main method accepts a single argument of type String array. This is called as Java command line arguments.


Get Started with Eclipse IDE

Example:

public class Example1 {
       public static void main (String[] args){
              for (String s: args){
                     System.out.println(s);
              }
       }
}

 To run the above example with the command line arguments in Eclipse, we pass the program arguments as shown below:

Select “Run Configurations” under “Run” tab:

Give the Arguments under “Arguments tab”

The output for the above example is,