Args Array
Every program you run, Java or not, can be given a list of words on its command line.
ls # No words on the command line
ls drills # One word on the command line
ls drills solutions # Two words on the command line
ls drills solutions whatever # Three words on the command line
Each word on the command line (also known as command-line parameters or arguments) is separated from the others by one or more spaces.
The shell - the program running in the terminal which receives and executes your commands - puts all words on the command line into an array which gets passed to the program you're running.
shell¶
A computer program that allows a user to interact with the system, primarily by executing other programs at the user's command. When you work in a terminal or console, the shell is your command-line interface (CLI) with the operating system.
- The
javacommand places the words it receives (other than its own namejavaand the name of the main class it's running) into a JavaStringarray which it passes to ourmainmethod.

- We could actually name
main's string array parameter something other thanargs.
public static void main(String[] stuffFromTheCommandLine) { ... }
- But then all the other Java programmers will point and laugh at us.
Drill¶
In main add:
System.out.println(args.length);
ShowMe.java, return to the terminal, and run it both with and without arguments.
java drills.ShowMe
java drills.ShowMe cat dog frog
Treat args just like any other array.
-
Check its
lengthfield. -
Iterate over it with a
forloop. -
Pass it to another method.
Drill¶
In main, add a for loop below the existing code.
* Open a new line.
* Type for and hit Ctrl-Space.
* Select for - iterate over an array from the list and hit Enter.
Eclipse creates a for loop for the nearest array it sees, which happens to be args.
* In the for loop body add:
System.out.println(i + ": " + args[i]);
ShowMe.java, return to the terminal, and run it both with and without arguments.
java drills.ShowMe
java drills.ShowMe cat dog frog