What String[] args do?

Last Updated on

Time needed: 5 minutes

In the previous examples we've made applications that simply execute an operation. What if we wanted to read some user input? That's what the String[] is there for: it contains all the arguments passed to an application.

Let's write a slightly modified program:

public class MyProject {
    public static void main(String[] args) {
        System.out.println("I was made without an IDE by " + args[0] + "!");
    }
}

Compile and run it with the javac command, same as before, but if you simply run it with the java command, it will no longer execute.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at MyProject.main(MyProject.java:3)

That cryptic error message means that our application tried to read the zeroth data inside an array, but it was completely empty. I'll explain what an array is later on, for now it's enough to know that it's a container for some data.

Everything that's written after the class name (MyProject) are treated as execution parameters, passed to the main method.

D:\IdeaProjects\MyProject> java MyProject.java you
I was made without an IDE by you!

If we want to pass a text separated by a space, we need to enclose it in quotation marks.

D:\IdeaProjects\MyProject> java MyProject.java "a great coder"
I was made without an IDE by a great coder!

Leave a Reply