.


Divya

Java While loop statement


In java while loops is used to execute a block of code while the specified condition is true.

Some time want the same block of code to run over and over again in a row.Example: Fetch multiple students data.In that case we can use while loop.

while (condition) {
    code block to be executed
}

Example

class while loop Example {
public static void main(String[] args) {
int a=1;
while(a<=7){
System.out.println(a);
a++;
}
}
}

Output :
1
2
3
4
5
6
7

do while loop

In java do while loop is similar to while loop but one key point is difference.First, the code within the block is executed and then condition is checked .if the the condition is true then code of block executed repeatedly .until the condition becomes false.

do {
    code block to be executed
}
while (condition);

Example

class do while loop Example1 {
public static void main(String[] args) {
int a=10;
do{
System.out.println(a);
a++;
}while(a<=20);
}

Output :
10
11
12
13
14
15
16
17
18
19
20

Example

class do while loop Example2 {
public static void main(String[] args) {
int a=10;
do{
System.out.println(a);
a++;
}while(a>=20);
}

Output : 10



.