Free Java Guide




These tutorials will introduce you to Java Language. You'll compile and run your own Java application, using Sun's JDK. It's very easy to learn java programming skills, and here parts, you'll learn how to write, compile, and run Java applications. Before you can develop corejava applications, you need to download the Java Development Kit (JDK).


PART-3

Java Loops (while, do-while and  for loops)

A loop is a section of code that is executed repeatedly until a stopping condition is met. A typical loop may look like:
 

while there's more data {
  Read a Line of Data
  Do Something with the Data
}

There are many different kinds of loops in Java including while, for, and do while loops. They differ primarily in the stopping conditions used.

For loops typically iterate a fixed number of times and then exit. While loops iterate continuously until a particular condition is met. You usually do not know in advance how many times a while loop will loop.

In this case we want to write a loop that will print each of the command line arguments in succession, starting with the first one. We don't know in advance how many arguments there will be, but we can easily find this out before the loop starts using the args.length. Therefore we will write this with a for loop. Here's the code:

Source Code

// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      int i;
    
      /* Now let's say hello */
      System.out.print("Hello ");
      for (i=0; i < args.length; i = i++) {
        System.out.print(args[i]);
        System.out.print(" ");
      }
      System.out.println();
  }

}
We begin the code by declaring our variables. In this case we have exactly one variable, the integer i. i

Then we begin the program by saying "Hello" just like before.

Next comes the for loop. The loop begins by initializing the counter variable i to be zero. This happens exactly once at the beginning of the loop. Programming tradition that dates back to Fortran insists that loop indices be named i, j, k, l, m and n in that order.

Next is the test condition. In this case we test that i is less than the number of arguments. When i becomes equal to the number of arguments, (args.length) we exit the loop and go to the first statement after the loop's closing brace. You might think that we should test for i being less than or equal to the number of arguments; but remember that we began counting at zero, not one.

Finally we have the increment step, i++ (i=i+1). This is executed at the end of each iteration of the loop. Without this we'd continue to loop forever since i would always be less than args.length.