Java Certification, Programming, JavaBean and Object Oriented Reference Books
Java for Statement

This tutorial will take you step by step through the process of understanding and using the for loop. The best way to learn is to compile and run these programs yourself (copy, paste, compile and run !). Comments such as /* this is a comment */ or // this is another comment are inserted to explain what does the line of code do. The programs are kept simple for the purpose of concentrating on the main idea in question.

Example 1: for statement with one control variable

  
class For1{ 
   public static void main(String args[]){
      
        for(int i=0; i<4; i++)
        System.out.println("i= "+i); 
   }
}      

When execution of the for statement is started, i=0 is executed (this is executed once only). Next i<4 is evaluated and if it evaluates to true then the loop is executed. Next i++ is executed. When i<4 evalutaes to false the loop terminates.

Example 2: for statement with two control variables

  
class For2{ 
   public static void main(String args[]){
      
        for(int i=0,j=2; i<4; i++, j++)
        System.out.println("i= "+i+"j= "+j); 
   }
}   

NOTE: i=0,j=2 separated by a comma. i++, j++ also separated by a comma. The statements separated by a comma are executed one after the other.

Example 3: nested for statements

  
class For3{ 
   public static void main(String args[]){
      
        for(int i=2; i<6; i++)
           for(int j=2; j<5; j++)
                System.out.println("i= "+i+"j= "+j); 
   }
}   

start: i=2; then the for loop controled by j is executed with j=2 to j=4. Next i = 3; then the for loop controled by j is executed j=2 to j=4 and so on.

Return to : Java Programming Hints and Tips