Java Notes2 PDF
Java Notes2 PDF
While loop is used when the number of iterations are not fixed or unknown. It is
an entry-controlled loop.
condition is a boolean expression which determines whether the loop will repeat
or not. It is executed for every iteration. The loop continues till the condition is
true.
Prepared By – Asmita Ranade
do-while loop
Syntax –
do
{
Block
} while ( condition ) ;
Do-while loop is used when the number of iterations are not fixed or unknown. It is an
exit-controlled loop. It gets executed at least once. Here, the condition is checked at the
end of every iteration i.e. at the end of the loop.
condition is a boolean expression which determines whether the loop will repeat or not.
It is executed for every iteration. The loop continues till the condition is true. It is an
optional expression. Prepared By – Asmita Ranade
Compare - for loop vs. while loop vs. do-while loop
Criteria for loop while loop do-while loop
Type of loop Entry-controlled Entry-controlled Exit-controlled
Use when there are Use when number of Use when the loop
When to use fixed number of iterations are not fixed statements should be
iterations or known. executed at least
once.
Initialization It can be done inside It should be done It can be done inside
of iteration the loop or before the before the loop. the loop or before the
variable loop. loop.
May get executed May get executed zero It gets executed at
zero times if the times if the condition is least once.
Execution
condition is false at false at first go.
first go.
Prepared By – Asmita Ranade
break statement
The break statement is used to terminate the currently executing loop. It allows an
immediate exit from a loop, bypassing any remaining code in the body of the loop.
When the loop is terminated using the break statement, program control resumes at the
next statement following the loop.
It can be used inside for loop, while loop and do-while loop.
When used inside nested loops, the break statement will break out of only the
innermost loop.
The break statement that terminates a switch statement affects only that switch
statement and not any enclosing loops.
Prepared By – Asmita Ranade
continue statement
The continue statement is used in loop when we need to jump to the next iteration of
the loop immediately. It forces the next iteration of the loop to take place, skipping any
code between itself and the conditional expression which controls the loop.
It is essentially the complement of break statement.
In while and do-while loops, a continue statement will cause control to go directly to
the conditional expression and then continue the looping process.
In case of for loop, the iteration/update expression of the loop is evaluated, then the
conditional expression is executed and then the loop continues.