OCA Java SE 8 Operators/Statements - Java for Statement








Java has two types of for statements.

The first is referred to as the basic for loop, and the second is called the enhanced for loop.

The Basic for Statement

The following code shows the syntax of a for loop.

for(initialization; booleanExpression; updateStatement) { 
}

The following steps are followed by the for loop.

  • Initialization statement executes
  • If booleanExpression is true continue, else exit loop
  • Body executes
  • Execute updateStatements
  • Return to Step 2

Each section is separated by a semicolon.

The initialization and update sections may contain multiple statements, separated by commas.

Variables declared in the initialization block of a for loop are only accessible within the for loop.

The variables declared before the for loop and assigned a value in the initialization block may be used outside the for loop because their scope precedes the for loop creation.

Let's take a look at an example that prints the numbers 0 to 9:

for(int i = 0; i < 10; i++) { 
  System.out.print(i + " "); 
} 

The local variable i is initialized first to 0.

The variable i is only in scope inside the for loop and is not available outside the loop.

The boolean condition is evaluated on every iteration of the loop before the loop executes.

The loop executes the update section, which in this case increases the value of i to 1.

The following code creates an Infinite Loop

for( ; ; ) { 
    System.out.println("Hello World"); 
} 

The following code shows how to add Multiple conditions to the for Statement. We can declare a variable, such as x, before the loop begins and use it after it completes.

The initialization block, boolean expression, and update statements can include extra variables.

The update statement can modify multiple variables.

int x = 0; 
for(long y = 0, z = 4; x < 5 && y < 10; x++, y++) { 
   System.out.print(y + " "); 
} 
System.out.print(x); 




Example 1

We cannot redeclare a variable in the initialization block. x in the following code is redeclared in the initialization block after already being declared before the loop.

int x = 0; 
for(long y = 0, x = 4; x < 5 && y < 10; x++, y++) {   // DOES NOT COMPILE 
   System.out.print(x + " "); 
} 

We can in the initialization block assigns a value to x but cannot declare it.

Example 2

We cannot use incompatible data types in the Initialization Block.

The variables in the initialization block must all be of the same type.

for(long y = 0, int x = 4; x < 5 && y<10; x++, y++) {   // DOES NOT COMPILE 
    System.out.print(x + " "); 
} 




Example 3

We cannot use Loop Variables Outside the Loop. x is defined in the initialization block of the loop, and cannot be used after the loop terminates.

x was only scoped for the loop, using it outside the loop will throw a compiler error.

for(long y = 0, x = 4; x < 5 && y < 10; x++, y++) { 
   System.out.print(y + " "); 
} 
System.out.print(x);  // DOES NOT COMPILE 

The for-each Statement

for-each loop is for iterating over arrays and Collection objects.

This enhanced for loop is shown in the following code.

for(datatype instance : collection) { 
}

In for-each loop declaration part we define a value to be iterated over.

The right-hand side of the for-each loop statement must be a built-in Java array or an object whose class implements java.lang.Iterable interface.

The variable type in the for-each loop declaration part matches the type of a member of the array or collection in the right-hand side of the statement.

On each iteration of the loop, the variable in the declaration part is assigned a new value from the array or collection on the right-hand side.

for-each Example 1

public class Main{
   public static void main(String[] argv){
     final String[] names = new String[3]; 
     names[0] = "A"; 
     names[1] = "B"; 
     names[2] = "C"; 
     for(String name : names) { 
       System.out.print(name + ", "); 
     }    /*ww w  .  j  ava  2  s .co m*/
   }
}

The code above generates the following result.

for-each Example 2

public class Main{
   public static void main(String[] argv){
//w ww  .  j  a  va 2 s . c  om
     java.util.List<String> values = new java.util.ArrayList<String>(); 
     values.add("A"); 
     values.add("B"); 
     values.add("C"); 
     for(String value : values) { 
       System.out.print(value + ", "); 
     } 
  }
}

The code above generates the following result.

for-each Example 3

The following code fails to compile since String type does not implements the java.lang.Iterable interface.

String names = "Lisa"; 
for(String name : names) {   // DOES NOT COMPILE 
   System.out.print(name + " "); 
} 

The following code fail to compile since the type is miss matched. It trys to match int to String.

String[] names = new String[3]; 
for(int name : names) {  // DOES NOT COMPILE 
   System.out.print(name + " "); 
} 

Comparing for and for-each Loops

The following two for statement are equivalent.

for(String name : names) { 
   System.out.print(name + ", "); 
} 
for(int i=0; i < names.length; i++) { 
   String name = names[i]; 
   System.out.print(name + ", "); 
} 

For objects that inherit java.lang.Iterable, there is a different conversion.

for(int value : values) { 
  System.out.print(value + ", "); 
} 

for(java.util.Iterator<Integer> i = values.iterator(); i.hasNext(); ) { 
   int value = i.next(); 
   System.out.print(value + ", "); 
} 

Nested Loops

Loops can contain other loops.

The following code that iterates over a two-dimensional array.

public class Main{
   public static void main(String[] argv){
        int[][] myComplexArray = {{5,4,3,2},{1,2,3,4},{5,6,7,8}}; 
        for(int[] mySimpleArray : myComplexArray) { 
          for(int i=0; i<mySimpleArray.length; i++) { 
            System.out.print(mySimpleArray[i]+"\t"); 
          } /*from  ww  w.  j  a va2s. c  o m*/
          System.out.println(); 
        } 
   }
}

We mixed a for and for-each loop in this example. The outer loops will execute a total of three times.

Each time the outer loop executes, the inner loop is executed four times.

The code above generates the following result.

Example for Nested Loops

Nested loops can include while and do-while, as shown in this example.

public class Main{
   public static void main(String[] argv){
        int x = 20; 
        while(x>0) { 
          do { //from  www . j  a va  2 s. c om
            x -= 2 ;
          } while (x>10); 
          x--; 
          System.out.print(x+"\t"); 
        } 
   }
}

The code above generates the following result.