Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects Delivering the MVP Forum

How does the args[] in the main work?

i guessed the answer correct but i dont understand how the program knows where args[0] and args[1] come from. Ca someone explain that to me? (in main.java by the user i entered (args[0], args[1])

2 Answers

andren
andren
28,558 Points

The args array is a parameter of the main method, as you probably know what calls the main method is Java itself, when it does so it passes in a string array based on the arguments that is provided when the program is run.

If you ran the program from the command line like this for example:

java Main Hello World

Then all the words typed after Main would be treated as arguments. So args[0] would be set to "Hello" and args[1] would be set to "World".

So the program gets the value of args[0] and args[1] from whatever is running the code. In this case that is the Treehouse code checker, which is likely programmed to pass in two specific names as arguments.

The method also includes a check that there is enough arguments and an error messsage if there is not:

if (args.length < 2) {
    System.out.println("Usage: java Main <first name> <last name>");
    System.err.println("<first name> and <last name> are required");
    System.exit(1);
}

Arguments were also discussed in the Arrays and Command Line Arguments video that appears earlier in this section.

Thanks! that makes sense. So for the greater picture: If i fil in a form on a webpage, could that be the args for the main.java?