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 following code shows the syntax of a for
loop.
for(initialization; booleanExpression; updateStatement) {
}
The following steps are followed by the for loop.
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);
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.
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 + " "); }
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
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.
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.
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.
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 + " "); }
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 + ", "); }
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.
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.