Writing your first Java "Hello World" application is pretty exciting. When you start your Java journey, you are told this is the syntax to write the program, and you just go along with it. Today, we will break down the reasons behind the main method of your Java code.
Let's consider the following "Hello World" code:
public class HelloWorld{
public static void main(String[] args) {
System.out.println("Hello - " +args[0]+" "+args[1]);
}
}
It has three main components: a class "Helloworld", a public method "main", and an array of strings "args".
1.The keyword class defines your Java class. As an object-oriented language, everything must be inside a class. It can have any name as long as your file name is the same. This tells the JRE which class to look for.
2.Then comes your main method. It has to be named "main" for the JRE to recognize it, as it calls the main method to execute your program.
Breaking down the method signature:
public – Access specifier. It has to be public for the JRE to call the function. Other access modifiers include private and protected, which cannot be called from outside the class.
static – The static keyword defines the method as a static method, meaning the JRE can call this method without creating an object of your class.
i.e instead of this -
HelloWorld obj = new HelloWorld();
obj.main(args);
it can directly call this -
HelloWorld.main(args);
void – The return type of your program. This has to be void so that when your program finishes, it actually terminates and returns nothing.
3.The parameter String[] args – This is called command-line arguments. Just like you pass information to methods inside the program, you can pass values to your main program as an array of arguments (you can call it "args" or literally any variable name).
Example on how to use it (use space to give multiple arguments):
java myprogram arg1 arg2
java HelloWorld There,General Kenobi
will give output -
If you are using eclipse you can pass this arguments in configuration option -
Top comments (0)