Flow Control and Exception Handling - while Statement
Syntax (JLS §14.11)
while( boolean expression ) {
statement(s);
}
- executes statement(s) repeatedly until the value of expression is false
- if the expression is false the first time, the statements will never execute
int i = 1;
while( i>3 ) {
System.out.println("This shouldn't print");
}
- both the break and continue statements can be used to alter the processing of a while loop
while( i < 10 ){
if( i == 5 ) break; // break out of loop
System.out.println(i);
i++;
}
while( i < 10 ){
if( i==5 ) {
i++;
continue; // force next loop
}
System.out.println(i);
i++;
}
Example Code
Traps
- non-boolean expression
- using '=' instead of '==' for boolean expression
|