The for Loop


When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop.

The top script is the syntax of the for loop. The bottom script is an example, whose statements are explained as below:
 for ( statement 1; statement 2; statement 3 ) {
   // code block to be executed
 }

 for ( int i = 0; i < 5; i++ ) {
   System.out.print( i );  
 // Output: 01234
  1. Statement 1 sets a variable before the loop starts (int i = 0).
  2. Statement 2 defines the condition (i<5) for the loop. If the condition is true, the loop will start over again. If it is false, the loop will end.
  3. Statement 3 increases a value (i++) each time the code block in the loop has been executed.
ArrayReverse.java (reversing an array by using another array)

 public class  ArrayReverse {
   public static void  main( String[ ] args ) {
     String[ ]  array = args[0].( " " );
     int   arrayLength = array.length;

     // Create a second array of the same length.
     String[ ]  reversedArray = new String[arrayLength];

     // Loop through the original array in a reverse direction.
     for ( int i =  - 1, j = 0; i >=0; i--, j++ )
       // Assign elements to the second array.
       reversedArray[j] = array[i];

     // Print the original array.
     for ( String word : array )  System.out.print( word + " " );
     // Print the arrow.
     System.out.println( " ⇒ (reverse) ⇒  " );
     // Print the reversed array.
     for ( String word : reversedArray )  System.out.print( word + " " );
   }
 }
shell> java ArrayReverse          




      Why should you never date a tennis player?    
      Because love means nothing to them.