While Loops in Java
While Loops in Java
Description
In computer programming, a loop is a sequence of instruction s that is continually
repeated until a certain condition is reached. Imagine you have to write a program
which performs a repetitive task such as printing 1 to 100. Writing 100 print
statements would not be wise thing to do. Loops are specifically designed to
perform repetitive tasks with one set of code. Loops save a lot of time. A loop is a
called the loop body executes and the Boolean expression is evaluated again. As
long as the expression is true, the statements in the loop body continue to execute.
A for loop, which is usually used as a concise format in which to execute loops
While Loops
The while loop is good for scenarios where you don't know how many times a
block or statement should repeat, but you want to continue looping as long as some
condition is true. A while statement looks like below. In Java, a while loop consists
followed by the body of the loop, which can be a single statement or a block of
You can use a while loop when you need to perform a task a predetermined
number of times. A loop that executes a specific number of times is a definite loop
or a counted loop. To write a definite loop, you initialize a loop control variable, a
another value is true, the body of the while loop continues to execute. In the body
of the loop, you must include a statement that alters the loop control variable.
Java Code
1. package loops;public class WhileLoopDemo { public static void main(String[] args) { int
var = 1; int limit=11; while (var <limit){ System.out.println("Loop counter: " + var)
; var++; } }}
Output
The key point to remember about a while loop is that it might not ever run. If the
test expression is false the first time the while expression is checked, the loop body
will be skipped and the program will begin executing at the first statement after the
while loop.
Important Points while using loops
Loop condition/expression can be true always, which makes our loop infinite.
It is very common to alter the value of a loop control variable by adding 1 to it,
or incrementing the variable. However, not all loops are controlled by adding 1
decrementing it.
do … while Loops
The do loop is similar to the while loop, except that the expression is not evaluated
until after the do loop's code is executed. Therefore the code in a do loop is
iteration. The
do...while loop checks the value of the loop control variable at the bottom of the
loop after one repetition has occurred. Below sample code explain do… while
loop.
Java Code
1. package loops;public class DoWhileLoopDemo { public static void main(String[] args) {
}while (i<10); }}
Output
Summary
The while loop is used for scenarios where you don't know how many times a
The do loop is similar to the while loop, except that the expression is not
Source: http://www.w3resource.com/java-tutorial/java-while-do-while-loop.php