Blogger templates

What's the use of "String[] args" on the main method

When we write some code in java, we write the main method with an array of String[] as the parameter. But why so?

As we’re on it, let’s have some discussion on why we write (String[] args) in the main method!
Firstly, I’ll assume that you have the basic idea of what a for-loop and array is. Otherwise do not continue.
Now, having that said, let’s change the test.java file a little.
Put the codes in the file and save it.

public class test{
    public static void main(String[] args){
        for(int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}

This code essentially just increase the variable named i while it is less than the array args’s length!
Then we just print the content of that perrticular array index.

Now compile it using CLI again. (using javac…..)
Now run it using the command below,
java test hi there everyone
This command might seem a little wired, but what it is basically doing is calling the main method in the test.class file and supplying an array like,
{“hi”,”there”,”everyone”}
to the method, and the codes in the method just prints them out like the picture below!


Some point from Wikipedia about its usages and why it’s here,
·         Java only starts running a program with the specific public static void main(String[] args)signature, and one can think of a signature like their own name - it's how Java can tell the difference between someone else's main() and the one true main().

·         String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.

No comments

Powered by Blogger.