Engineering Full Stack Apps with Java and JavaScript
The “while loop” is an alternative to “for loop”. a “for loop” is usually used when the number of times the block is to be executed is known. A “while loop” is usually used when the number of times the block is to be executed is not known, like prompting the user whether to stop executing during every iteration.
The syntax of “while loop” is:
while (<condition>) <statements>;
Example:
int i=0;
while(i<5)
{
System.out.print(i);
i++;
}
If you initialize i to 5, the loop will never get executed and nothing will be printed.
In a while statement, evaluation of the expression happens at the beginning of the loop and the body of the loop may never be executed if the first evaluation of the logical expression evaluates to false. The do-while statement is similar to a while loop except that the body of the loop always executes at least once.
The syntax of do-while loop is:
do <statement> while (<condition>);
Example:
int j=0;
do
{
System.out.print(j);
j++;
}
while(j<5);
If you initialize j to 5 in this example, the loop will get executed once even is while condition is false.
Note that the semicolon (;) after while in do-while is required always. If you put a semicolon (;) after “while” in a regular “while statement”, it will mean an empty statement and the while loop might go into an infinite loop. See quiz for example.
The break statement terminate the current loop (while, for, for-each, or do-while) or the switch statement and passes control to the next statement following the loop. The break statement cannot be used outside of a loop or switch.
Infinite loops are useful to avoid writing a logical condition for a loop just for the sake of writing. Most infinite loops are designed to terminate using the break statement. However we should be careful about unintentional infinite loops which are dangerous.
The continue statement bypass remaining statements in a loop in the current iteration and reaches end of the loop. It will then continue with next iteration of the loop from beginning. The continue statement cannot be used outside of a loop.
Loops can be nested within each other. Any nested combination of the for, for-each, while, or do-while loops is allowed.
If we use break and continue statements in the inner loop, it will only break out or skip to the end of the inner loop and not the outer loop.
Question 1
Will code compile; if yes, find output:
int i=0;
while(i<5);
{
System.out.print(i);
i++;
}
Answer 1
Code will compile, but will not print anything.
Here while statement is followed by a semicolon, which is an empty statement and hence the while loop will go into an infinite loop. So remainder is not executed. The block within braces ({}) though looks like while body block, is just an inner block. To know more about blocks, refer to javajee.com/blocks-and-methods-in-java.