While loop in java with example

There are several looping statements available in java. One of them is while loop in java.
While loop is used to execute some statements repeatedly until condition returns false. If number of iterations are not known beforehand, while loop is recommended.

The syntax for while loop in java

Let’s take a very simple example:
Print number from 1 to 10 using while loop

1

2

3

4

5

6

7

8

9

10

11

12

publicclassWhileLoopMain{

publicstaticvoidmain(String[]args){

inti=1;

while(i<11)

{

System.out.print(" "+i);

i++;

}

}

}

Output:

1 2 3 4 5 6 7 8 9 10

If you are still confused with above concept, let’s understand it with the help of flow diagram.

Let’s try to print only even numbers now.

1

2

3

4

5

6

7

8

9

10

11

12

13

publicclassWhileLoopMain{

publicstaticvoidmain(String[]args){

inti=1;

while(i<11)

{

if(i%2==0)

System.out.print(" "+i);

i++;

}

}

}

Output:

2 4 6 8 10

Exercise

If you are given an array of integer, you need to find an element in that array.

Input:

{32,45,53,65,43,23}

You need to write a program to search an element in the array.If element is found in the array, return “PRESENT” else return “NOT PRESENT”

I would recommend you to try it yourself and then look at below code.

Program:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

packageorg.arpit.java2blog;

publicclassWhileLoopMain{

publicstaticvoidmain(String[]args){

WhileLoopMain bse=newWhileLoopMain();

intarr[]={32,45,53,65,43,23};

System.out.println(bse.findElementInArr(arr,53));

}

publicStringfindElementInArr(intarr[],intelementTobeFound)

{

inti=0;

while(i<arr.length)

{

if(arr[i]==elementTobeFound)

{

System.out.println(elementTobeFound+" is present in the array ");

return"PRESENT";

}

i++;

}

return"NOT PRESENT";

}

}

Output:

53 is present in the array
PRESENT

Infinite while loop

You need to be careful with condition you provide in while loop otherwise, you may end up creating infinite while loop.For example:
Let’s say you want to print number from 10 to 1 and you use below code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

packageorg.arpit.java2blog;

publicclassWhileLoopMain{

publicstaticvoidmain(String[]args){

inti=10;

while(i>0)

{

System.out.print(" "+i);

i--;

}

}

}

Output:

10 9 8 7 6 5 4 3 2 1

Now in above code, instead of i–, you have put i++. In this code,loop will go into infinite loop.