Program 5.3: One Last Hello World

In the final version of the Hello program in Chapter 3 you needed a loop which would print each of the command line arguments in succession, starting with the first one. You knew in advance how many arguments there were from the args.length variable.

This problem was solved with a while loop, and indeed that was a valid and useful solution. However while loops are more commonly used for problems where there isn't a known number of iterations when the loop starts. Although while loops are well suited to that type of problem, that particular variation of a loop, where therešs a counter that counts up to a certain variable, is so common that there's a somewhat redundant but nonetheless useful shorthand for this operation. That shorthand is a for loop, and you will now see how to solve this problem with a for loop. Here's the code.

// This is the Hello program in Java

class Hello {

   public static void main (String args[]) {
     System.out.print("Hello ");
     for (int i=0; i < args.length; i++) {
       System.out.print(" ");


Copyright 1996 Elliotte Rusty Harold
This Chapter