Using the args Array - Exercise

Contact Us or call 1-877-932-8228
Using the args Array - Exercise

Using the args Array

Duration: 5 to 10 minutes.
  1. Note that there has been an array declaration in all of our examples thus far; the array of strings passed to main: args
    • These are the additional words on the command line.
  2. Copy to, and modify that to loop through args to print each element (remember to rename the class in the declaration line).
  3. Then run the program with something like java HelloArgs From Me and see what happens.


public class HelloArgs {
	public static void main(String[] args) {

		// using indexed loop
		for (int i = 0; i < args.length; i++)

		// using foreach loop
		for (String a : args)

The for loop iterates through the array; each separate word on the command line becomes one element in the array (note that java HelloArgs is not part of the array).