Java while loop With Examples

Java while loop is used to execute a block of statements continuously till the given condition is true. Earlier we looked into java for loop.

Java while loop

While loop in java syntax is as follows.

The expression for while loop must return boolean value, otherwise it will throw compile time error.

While loop java flow diagram


Java while loop example

Here is a simple java while loop example to print numbers from 5 to 10.

Notice that I am increasing value of i inside while loop, otherwise the while loop will never terminate and we will have an infinite loop. The only way to terminate the program running in infinite loop is to manually quit it or when the JVM runs out of memory.

Also note that if boolean expression returns false then statements inside while loop won’t execute. So there is a chance that statement inside while loop will never execute.

Java while loop with Iterator

Java while loop is used a lot with iterator in java. Let’s see a short example of iterating over an ArrayList using while loop.

It will print output as below.

while true java

Sometimes we intentionally want our while loop to run infinitely. In that case we can use while true loop. An example could be looking for a file at specific location continuously and if found then process it. Below is a pseudo code example of while true loop in java.

If we run above program, we will have to manually quit it using Ctrl+C on terminal. If you are using Eclipse then there is a red button to terminate the current running program.


Let’s say you have written some code inside a class and it’s work in progress so you don’t want to get it executed. Can we just wrap it inside while false loop so that it will not execute at all?

Well java compiler is smart enough to give us compilation error that code is unreachable. Below are images from Eclipse editor as well as when we are trying to compile the program from terminal.


But there is another way to achieve this, use a dummy boolean variable and the compiler error will be gone.

That’s all about java while loop, I hope you get clear idea how and when to use while loop in java.

Reference: Oracle Documentation

By admin

Leave a Reply