Java Programming

5.3 While loop

Java while loop is used to execute statement(s) until a condition holds true.
SYNTAX
while (condition(s)) {
// statements
}

If the condition holds true then the body of loop is executed, after execution of loop body condition is tested again and if the condition is true then body of loop is executed again and the process repeats until condition becomes false.

1. Condition is always evaluated to true or false and if it is a constant, For example while (c) { …} where c is a constant then any non zero value of c is considered true and zero is considered false.

2. You can test multiple conditions such as

while ( a > b && c != 0) {
// statements
}

Loop body is executed till value of a is greater than value of b and c is not equal to zero.

3. Body of loop can contain more than one statement.
For multiple statements you need to place them in a block using {} and if body of loop contain only single statement you can optionally use {}.

It is recommended to use braces always to make your program easily readable and understandable.

Download for more knowledge

https://play.google.com/store/apps/details?id=ab.java.programming

Leave a comment