All the beginners in Java language are first taught the Hello World program, which although very simple looking, contains a lot of the functionality secrets of Java.
The first method that a new java programmer writes is the “main” method.
The entire Hello World program looks something like the following:public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
The output, obviously is:
Hello World
Let us explore the main method and all its keywords one by one:
The first thing one should know that the execution of a java program starts from the main function. After loading the program, the Java Virtual Machine (JVM) scans the program to search for “public static void main (String[] args)”
Public: “public” is an access-specifier and it means that the method can be called from outside of the class. The main method has to public so that the JVM can call it and begin the program.
Static: “static” means that only one copy of the main function is shared between all objects of the class and one doesn’t have to initialize a class object to call the main method. (For more information on “static”, click here)
Void: “void” is a return type. It indicates that the main function does not return anything. This is quite logical, as the main function is called implicitly by the JVM and not by another function. So it has no function to return value to.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
If you are operating from the command prompt/terminal, and you enter
java HelloWorld I’m Batman
The output will be:
Hello World
I’m
Batman
If you type: java HelloWorld “I’m Batman”, the output is:
Hello World
I’m Batman
If you are using the Eclipse IDE, you can enter the “program arguments” from Run>Run Configurations>(x)= Arguments (That’s the second tab) and then enter your arguments.
No comments:
Post a Comment