Java Reference
In-Depth Information
A for-loop statement:
for (initialization; condition-expression; expression-list)
Statement
Equivalent while-loop Statements:
Initialization
while (condition-expression) {
Statement
Expression-list
}
You can print all integers between 1 and 10 using a while -loop as shown:
int i = 1;
while (i <= 10) {
System.out.println(i);
i++;
}
The above code can also be rewritten as
int i = 0;
while (++i <= 10) {
System.out.println(i);
}
or
int i = 1;
while (i <= 10) {
System.out.println(i++);
}
A break statement is used to exit the loop in a while -loop statement. You can rewrite the above example using
a break statement as follows. Note that the following piece of code is written only to illustrate the use of a break
statement in a w hile -loop; it is not a good example of using a break statement.
int i = 1;
while (true) { // Cannot exit the loop from here
if (i <= 10) {
System.out.println(i);
i++;
}
else {
break; // Exit the loop
}
}
Search WWH ::




Custom Search