The for statement in Java

  1. Syntax of the for statement in Java:

    
          for ( initialization; boolean expression; update )       
             one-statement
    
    for ( initialization; boolean expression; update ) { more-than-one-statement }

  2. A for loop can ALWAYS be replaced by a while loop:

    
          for ( initialization; boolean expression; update )       
             statement
    
    initialization; while ( boolean expression ) { statement update; }

  3. Example: sum an array

    
          A is an integer array of 10 elements
    
    sum = 0; for ( i = 0; i < 10; i = i + 1 ) sum = sum + A[i];
    sum = 0; i = 0; while ( i < 10 ) { sum = sum + A[i]; i = i + 1; }