# While loop in Java

A while loop repeatedly executes the same set of instructions until the controlling condition is true.

### 1. Syntax

Its general form is:

```while(condition){
// loop body
}```
• condition is any boolean expression.
• Loop body is executed until the condition is true. Once it becomes false, statements just after the loop body are executed.
• If the loop body contains only one statement then curly brackets are not required. If it contains more than one statement then the curly braces are necessary.
• A null statement(only semi-colon) is also a valid loop body.

### 3. An example

The code below computes the sum of first 100 integers and then prints it:

```// Demonstration of while loop
public class While_demo {
public static void main(String[] args){
int sum = 0, i=0;

while( i <= 100 ){
sum = sum + i;
i = i+1;
}

System.out.println("Sum of first 100 integers is: " + sum);
}
}```

The output of the above code is:

`Sum of first 100 integers is: 5050`

Let’s see how this code works :

• First the value of sum and i, both are assigned to 0.
• After 1st iteration: sum = sum + i = 0 + 0 = 0, i = i+1 = 0+1 = 1
• After 2nd iteration: sum = sum + i = 0 + 1 = 1, i = i+1 = 1+1 = 2
• After 3rd iteration: sum = sum + i = 1 + 2 = 3, i = i+1 = 2+1 = 3
• After 4th iteration: sum = sum + i = 3 + 3 = 6, i = i+1 = 3+1 = 4
• After 5th iteration: sum = sum + i = 6 + 4 = 10, i = i+1 = 4+1 = 5
• .
• .
• After 100th iteration: sum = sum + i = 4950 + 100 = 5050, i = i+1 = 100+1 = 101
• Since i = 101, the condition i<=100 becomes false and loop breaks. The next line of the code is a print statement which prints the value of the computed sum.

### 4. Empty loop body

As stated earlier, a null statement is also a valid loop body. Sometimes the control expression can itself handle a lot of details, in those cases loop bodies are unnecessary. Like in the example below, a timer is set to 30; when it decreases down to 0, the print statements are triggered.

```// Demonstration of empty while body
public class While_empty_body {
public static void main(String[] args){
int i=30;

while(--i > 0)
; // Null statement, Also no curly braces required as it is a single statement

System.out.println("Timer: " + i);
System.out.println("Timer expired!");
}
}```

The output is :

```Timer: 0
Timer expired!```

### 5. Infinite while loop

There are situations where it is desirable to run a loop for as long as possible.

• Like polling, when you continuously check for resources if they are available or not.
• Or continuously taking input from the keyboard.

The code below, continuously takes input from the keyboard character by character.

```// Demonstration of infinite while loop
public class Infinite_while {
public static void main(String[] args)throws java.io.IOException{
char ch;
System.out.println("Start entering the characters: ");
while(true){
if(ch != '\n') {
System.out.println("New character : " + ch);
}
}
}
}```

The output is :

```Start entering the characters:
J
New character : J
A
New character : A
V
New character : V
A
New character : A
IS Great
New character : I
New character : S
New character :
New character : G
New character : r
New character : e
New character : a
New character : t
...
// So on```

This example is a bit involved. Lets understand this, one at a time:

• System.in.read() reads input from the keyboard, character by character and returns them as integers. We cast them again to characters. If the character inserted was not a newline(‘\n’) character, it is printed back.
• throws java.io.IOException was needed  to handle input errors because it uses System.in.read().
• Even if you feed a lot of characters at once, it will read them one by one(like IS Great was fed).
• When you press ctrl + C  the code terminates.

### 6. Processing Arrays with while loop

Loops give you a lot of power when you have to do something repititive. In the example below we replace the value of an array element by its square.

```// Demonstration of arrays in while loop
public class Processing_arrays {
public static void main(String args[]){
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int i=0;
while(i < arr.length){
arr[i] = arr[i]*arr[i];
System.out.println(arr[i]);
++i;
}
}
}
```

The output is:

```1
4
9
16
25
36
49
64
81```

You can use nested while loops to process multi-dimensional arrays.

### 7. Nesting While loops

If one while loop contains another while loop inside its body then the while loops are said to be nested. This nesting can go on upto any level. The code below shows two-level nesting i.e two while loops are nested one-inside another:

```// Nesting while loops
public class Nesting {
public static void main(String[] args){
int i=0;
while( i <= 5 ){
int j = 0;
while( j <= i ){
System.out.print(j + " ");
++j;
}
System.out.println();
++i;
}
}
}
```

The output is:

```0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5```

Note that you could have easily replaced any of the while loops with some other loop, say for-loop or do-while loop.

### 8. Use of break in a while loop

There are occasions when you no longer want to iterate over all the elements because some condition has already been met. In those cases, you have to terminate the loop prematurely. break is a keyword used specifically for this purpose.

```// Breaking out of while loop at will
public class Break {
public static void main(String[] args){
int i = 8;
while( i > 0 ){
System.out.println("i = " + i);
if(i==5){
break;
}
--i;
}
System.out.println("While Loop Ended!");
System.out.println("i = " + i);
}
}```

The output is :

```i = 8
i = 7
i = 6
i = 5
While Loop Ended!
i = 5```

break, takes you out of the loop by one level. Had there been another loop surrounding the while loop in the previous example, internal loop would have been broken but the control would have still been surrounded by the external loop. Depending on the need, you might have used another break.

### 9. Use of continue in a while loop

Sometimes you want to skip rest of the instructions in a loop but you still want to continue running the loop, continue is a statement made specifically for this purpose.

```// Demo of continue statement in while loop
public class Continue_demo {
public static void main(String[] args){
System.out.println("Odd numbers from 0 to 10 are :");
int i=0;
while( i < 10 ){
i = i + 1;
if( i%2 == 0 ){
continue;
}
System.out.println(i);
}
}
}```

The output is :

```Odd numbers from 0 to 10 are :
1
3
5
7
9```

In case when i is divisible by 2, the continue statement sends the control to the start of the loop where the condition is checked. Then the statements in the while loop execute again from the start.

### 10. Labelled while loop

You can label a while loop using any valid Java token followed by a colon. Like in:

```labelName: while( condition ){
// Some statements
}```

Labelling can be used for many uses. For example, break with label can be used to break out of a series of nested loops to the end of a labelled loop.

```// Demo of a labelled while loop
public class Labelled_while_loop {
public static void main(String[] args){
int i = 0, j = 0, k = 0;

first: while( i < 5 ){
System.out.println("Inside first loop!");

second: while( j < 5 ){
System.out.println("Inside second loop!");

third: while( k < 5 ){
System.out.println("Inside third loop!");
break first;
}
System.out.println("third loop ended!");
}
System.out.println("second loop ended!");
}
// Control flows here on calling break first;
System.out.println("first loop ended!");
}
}```

The output is :

```Inside first loop!
Inside second loop!
Inside third loop!
first loop ended!```

### Note for C/ C++ programmers

In Java(unlike C/C++), condition can only be a boolean expression i.e. it should evaluate to literal true or false and nothing else. (In C/C++ any non-zero or non-NULL value acts as true and NULL and zero act as false. )