The for loop in Java

// This is the Hello program in Java
 
 class Hello {
 
   public static void main (String args[]) {
 
     System.out.print("Hello ");   // Say Hello
     for (int i = 0; i < args.length; i = i + 1) { // Test and Loop
       System.out.print(args[i]);  
       System.out.print(" ");
     }
     System.out.println();  // Finish the line
  }
 
}

Multiple Initializers and Incrementers

Sometimes it's necessary to initialize several variables before beginning a for loop. Similarly you may want to increment more than one variable. Java lets you do this by placing a comma between the different initializers and incrementers like this:

for (int i = 1,  j = 100;  i < 100;  i = i+1, j = j-1)  {    
    System.out.println(i + j); 
}

You can't, however, include multiple test conditions, at least not with commas. The following line is illegal and will generate a compiler error.

for (int i = 1,  j = 100;  i <= 100, j > 0;  i = i-1, j = j-1) {    

To include multiple tests you need to use the boolean logic operators && and || which will be discussed later.


Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified August 8, 1997