Site Search:

Create and use for loops including the enhanced for loop

Back OCAJP


A basic for loop has the following structure:
for(variable initializing statements; booleanExpressions ;  update statements) {//body}
When there is only one body statement, {} can be omitted.

Let's first take a look at some working examples.

The following example shows variable initialization statements and update statements can have one or more variables, as long as they are separated by comma (,) and have the same type.
The variable update can happen in both update states or in the loop body.
Loop continues as long as booleanExpressions is evaluated to true.


OCAJP>cat test.java 
class test {
  public static void main(String[] args) {
    for(int i = 0, j = 0; i < 5; i+=2) {
      i --; ++j;
      System.out.println("i="+i+",j="+j);
    }
    //System.out.println("j="+j);  //not compile 
    //System.out.println("i="+i);  //not compile
  }
}
OCAJP>javac test.java 
OCAJP>java test
i=-1,j=1
i=0,j=2
i=1,j=3
i=2,j=4
i=3,j=5


All the loop sections are optional, the following is an infinite loop which does nothing.

OCAJP>cat test.java 
class test {
  public static void main(String[] args) {
    for(;;){}
  }
}
OCAJP>javac test.java 
OCAJP>java test
^COCAJP>


We we need to iterate through an array or collection objects, we can use enhanced for loop.
for(datatype instance: collection) {//body}

datatype have to match the collection member's datatype, the collection have to be an array or class implements java.lang.Iterable.


OCAJP>cat test.java 
class test {
  public static void main(String[] args) {
    int[] a = {1,2,3,4,5};
    for(int i : a) {
      System.out.print("i = " + i + " ");
      //if(a[i] == 5) System.out.println(); //java.lang.ArrayIndexOutOfBoundsException: 5
      System.out.println("a["+ (i-1) + "]=" + a[i-1]);
      //System.out.println("a["+ i-1 + "]=" + a[i-1]);  //error: bad operand types for binary operator '-'
    }
  }
}
OCAJP>javac test.java 
OCAJP>java test
i = 1 a[0]=1
i = 2 a[1]=2
i = 3 a[2]=3
i = 4 a[3]=4
i = 5 a[4]=5
Back OCAJP