Online Software Educational Training - IT Tutorials - Online Education Training for Computer Software


Home

JAVA PROGRAMMING

Iteration Statements ( do-while, while, for) 

The  while statement

 You use a while statement to continually execute a block of statements while a condition remains true. The general syntax of the while statement is: 
while (expression) {
statement
}

First, the while statement evaluates expression, which must return a boolean value. If the expression returns true, then the while statement executes the statement(s) associated with it. The while statement continues testing the expression and executing statements until the expression returns false. 

A sample code using while






The do-while statement

Java provides another statement that is similar to the while statement--the do-while statement. The general syntax of the do-while is: 

do {
statement
} while (expression);

Instead of evaluating the expression at the top of the loop, do-while evaluates the expression at the bottom. Thus the statements associated with a do-while are executed at least once.

A sample code using do-while





The  for  statement

The for statement provides a compact way to iterate over a range of values. The general form of the for statement can be expressed like this: 
for (initialization; termination; increment) {
statement
}

initialization is a statement that initializes the loop--it's executed once at the beginning of the loop. termination is an expression that determines when to terminate the loop. This expression is evaluated at the top of each iteration of the loop. When the expression evaluates to false, the loop terminates. Finally, increment is an expression that gets invoked for each iteration through the loop. Any (or all) of these components can be empty statements. 

A sample code using for






Previous

Next