Java Reference
In-Depth Information
In this example, the enumeration defines four values, spring , summer , fall , and winter , so the variable
season is assigned each of these values in turn, as the output shows.
TRY IT OUT: The while Loop
You can write the program for summing integers again using the while loop, which shows you how the
loop mechanism differs from the for loop:
public class WhileLoop {
public static void main(String[] args) {
int limit = 20; // Sum from 1 to this value
int sum = 0; // Accumulate sum in this
variable
int i = 1;
// Loop counter
// Loop from 1 to the value of limit, adding 1 each cycle
while(i <= limit) {
sum += i++;
// Add the current value of i
to sum
}
System.out.println("sum = " + sum);
}
}
WhileLoop.java
You should get the following result:
sum = 210
How It Works
The while loop is controlled wholly by the logical expression that appears between the parentheses that
follow the keyword while . The loop continues as long as this expression has the value true , and how
it ever manages to arrive at the value false to end the loop is up to you. You need to be sure that the
statements within the loop eventually result in this expression being false . Otherwise, you have a loop
that continues indefinitely.
How the loop ends in the example is clear. You have a simple count as before, and you increment i in
the loop statement that accumulates the sum of the integers. Sooner or later i will exceed the value of
limit , and the while loop will end.
You don't always need to use the testing of a count limit as the loop condition. You can use any logical
condition you want.
Search WWH ::




Custom Search