Java while loop

Filed Under: Java

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.


while (expression) {
    // statements
}

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

While loop java flow diagram

java while loop, while loop in java

Java while loop example

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


package com.journaldev.javawhileloop;

public class JavaWhileLoop {

	public static void main(String[] args) {

		int i = 5;
		while (i <= 10) {
			System.out.println(i);
			i++;
		}
	}
}

java while loop example

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.


List<String> veggies = new ArrayList<>();
veggies.add("Spinach");
veggies.add("Potato");
veggies.add("Tomato");

Iterator<String> it = veggies.iterator();

while(it.hasNext()) {
	System.out.println(it.next());
}

It will print output as below.


Spinach
Potato
Tomato

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.


package com.journaldev.javawhileloop;

public class WhileTrueJava {

	public static void main(String[] args) {
		while(true) {
			System.out.println("Start Processing");
			// look for a file at specific directory
			// if found then process it, say insert rows into database
			System.out.println("End Processing");
			
			//  wait for 10 seconds and look again
			try {
				Thread.sleep(10*1000);
			} catch (InterruptedException e) {
				System.out.println("Thread Interrupted, exit now");
				System.exit(0);
			}
		}
	}

}

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.

while true java, java infinite while loop

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.

while loop java unreachable code compiler error

while loop java compiler error, while false java

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


boolean mutex = false;
while(mutex) {
	System.out.println("incomplete code");
}

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

Comments

  1. Adam says:

    while(true){

    System.out.println(“Keep posting these tutorials”);

    System.out.println(“Thank you very much”);

    }

    1. Pankaj says:

      Thanks a lot for the appreciation, I really liked the way you have put it.

  2. Alex Smith says:

    I have studied a lot about the java while loop function. It is a very helpful function and it is required now in mostly in every program. The function is very much helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages