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(args[i]);
System.out.print(" ");
}
System.out.println();
}
}