Java Reference
In-Depth Information
The for-each Statement
Java 5 introduced an enhanced
for
loop, which is called a
for-each
loop. It is used for iterating over elements of
arrays and collections. This section is included here to complete the list of statements that lets you loop through a
group values. Please refer to the chapters on arrays and collections for more detailed explanation of the
for-each
loop. The general syntax for a
for
-
each
loop is as follows:
for(Type element : a_collection_or_an_array) {
// This code will be executed once for each element in the collection/array.
// Each time this code is executed, the element variable holds the reference
// of the current element in the collection/array
}
The following snippet of code prints all elements of an
int
array
numList
:
int[] numList = {10, 20, 30, 40};
for(int num : numList) {
System.out.println(num);
}
10
20
30
40
The while Statement
A
while
statement is another iteration (or, loop) statement, which is used to execute a statement repeatedly as long
as a condition is true. A
while
statement is also known as a
while
-loop statement. The general form of a
while
-loop
statement is
while (condition-expression)
Statement
The condition-expression must be a
boolean
expression and the statement can be a simple statement or a
block statement. The condition-expression is evaluated first. If it returns
true
, the statement is executed. Again,
the condition-expression is evaluated. If it returns
true
, the statement is executed. This loop continues until the
condition-expression returns
false
. Unlike the
for
-loop statement, the condition-expression in a
while
-loop
statement is not optional. For example, to make a while statement infinite loop, you need to use the
boolean
literal
true
as the condition-expression.
while (true)
System.out.println ("This is an infinite loop");
In general, a
for
-loop statement can be converted to a
while
-loop statement. However, not all
for
-loop
statements can be converted to a
while
-loop statement. The conversion between a
for
-loop and a
while
-loop
statement is shown below.