Java while loop Complete Tutorial

In this section, we will learn what the while loop is and how to use it in Java.

The while Loop in Java

In programming, there are times that we want to repeat the execution of a block of code until a condition is met.

For example, let’s say we have a char variable named alpha and the initial value of this variable is a. There’s a block of code that if we run it, it will increase the value of this variable by one. So every time we run that block of code, the value of this alpha variable changes to the next alphabet character (b, c, d and e etc.).

What we want here is a loop that can repeat the execution of that block until the value of the alpha variable reaches the value z.

This is a candidate that we can use the while loop statement.

Before we write down and run the example above, let’s see the structure of while loop.

Java while loop syntax

while (condition) {
  // the code block to be executed
}

while keyword: To create a while loop we start with the keyword while.

( ): The parentheses that come after the while keyword, is used to set the condition of the loop. The condition here can be like while the value of a variable is not equal to something, repeat the loop.

Note: as long as the result of the condition is true, the body of the while loop will run.

Also, the true and false values can be used as the value of the condition. Of course, in such case, the value true will cause the loop to repeat itself indefinitely (unless we use statements like break; or return; in the body of the loop to stop it at some point). Also, if we put the value false as the condition of the loop, the body will not run at all because the condition is already false!

{ }: The body of the while loop starts from the opening brace { and ends right at the closing brace }.

Note: every time the engine executes the body, the condition will be checked again.  

Example: creating a while loop in Java

public class Simple {
    public static void main(String[] args) {
        char character = 'a';
        while (character != 'z'){
            System.out.print(character+", ");
            character++;
        }
    }
}
Output: 
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y,

How does while loop work?

As mentioned in the data-type section, char is another integer data-type and so it is possible to apply the ++ operator on a variable of this type.

In this example, the value of the character variable is first set to `a` and next we use this variable as the condition in the while loop. Basically, the condition of the loop is to check the value of the character variable and as long as the value is not equal to z, the body of the loop should be executed.

In another word, until the value of the character variable reaches the value z, the condition of the while loop is true and so the body of that loop will run over and over again.

Note: in the body of the loop we used ++ operator to increase the value of the character variable.

Basically, what we did here is to ensure the loop will not run indefinitely.

This is an important note to remember: Design the body of a loop in a way to affect the condition of the loop so it doesn’t run forever!

How to exit while loop in Java?

By default, as long as the condition of a while loop is true, its body will be executed.

But if we want to end the work of a while loop, we can use statements like break or the return in order to break and exit from a while loop before its condition becomes false and exit normally.

Note: please check the return and the break sections if you’re not familiar with these statements.  

In short, if you use the break statement in the body of a while loop, the Java execution engine will break the while loop and continue from the instructions that come after the while loop. This means the execution engine will still stay in the method that the while loop is created in.

On the other hand, using the return statement not only breaks the while loop but also returns from the method where the while loop is declared.

Example: using break statement in while loop

class Main{
	public static void main(String[] args) {
		int num = 0; 
		System.out.println("Before the call to the while loop");
		while(num<100){
			num++; 
		}
		System.out.println("After the call to the while loop. \nAlso the value of the num variable is: "+num);
	}
}
Output: 
Before the call to the while loop
After the call to the while loop.
Also the value of the num variable is: 100

Java while loop continue statement

Other than entirely breaking a while loop, sometime we might just want to break the current iteration and move on to the next iteration of the same while loop!

This is where we can use the continue statement!

We covered this statement in the continue section but in short, using this statement will skip the current iteration of a loop and will jump to the next iteration.

Example: using continue statement in while loop

class Main{
	public static void main(String[] args) {
		int num = 0; 
		System.out.println("Before the call to the while loop");
		while(num<5){
			num++;
			if (num>3){
				continue;
			}
			System.out.println(num);
		}
		System.out.println("After the call to the while loop.");
	}
}
Output: 
Before the call to the while loop
1
2
3
After the call to the while loop.

Java Infinite while loop

If we put a condition for a while loop that always returned true, then the body of that loop will never stop! This is a condition that is known as infinite while loop.

We seldom need to create an infinite loop in a program, but if ever you need to create such loop, the simplest method to do so is to use the value true as the condition of a while loop.

That way, the condition will be true for as long as the program is running.

Example: creating Infinite while loop in Java

class Main{
	public static void main(String[] args) {
		int num = 0; 
		System.out.println("Before the call to the while loop");
		while(true){
			// the body of the loop... 
		}
		System.out.println("After the call to the while loop.");
	}
}

Note: because this loop is infinite, the statement after the while loop will never appear on the output.

Nested while loops in Java

There’s no limit to what we can put in the body of a while loop! This is including the use of another while loop!

The use of a while loop within the body of another while loop is known as nested while loop.

Example: creating nested while loop in Java

class Main{
	public static void main(String[] args) {
		int num1 = 0; 
		int num2 = 0; 
		System.out.println("Before the call to the while loop");
		while(num1<10){
			num1++;
			while(num2<10){
				num2++;
			}
			System.out.println("The value of the num2 is: "+num2);
			num2 = 0; 
		}
		System.out.println("After the call to the while loop.");
	}
}
Output: 
Before the call to the while loop
The value of the num2 is: 10
The value of the num2 is: 10
The value of the num2 is: 10
The value of the num2 is: 10
The value of the num2 is: 10
The value of the num2 is: 10
The value of the num2 is: 10
The value of the num2 is: 10
The value of the num2 is: 10
The value of the num2 is: 10
After the call to the while loop.

More to Read:

Java for loop Tutorial

Java do-while loop

Java break statement

Java continue statement

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies