While Loop in Java

The while loop contineously executes a block of statements while a particular condition is true

The structure of while loop is:

While(condition)
{
	// do something
}

Meaning of this above piece of code is: As long as the condition mentioned in the while loop holds true, the //do something part will execute. Whenever the condition becomes false, the loop will break and the control goes to the next statement after the loop.

Example

public class WhileDemo {

	// we want to print 10 to 1 backwards
	public static void main(String[] args) {
		int i = 10; // initiate the count
		
		while (i > 0) { // while checks if i is greater than 0
			System.out.print(i + " ");
			i--; // decrease the value of i by 1
		}
	}
}
Try It

The above program prints:

10 9 8 7 6 5 4 3 2 1

Why did we put i-- statement inside the while loop? What could have happened otherwise?

We need to remember that we used the condition “when I is greater than ZERO” and we initiated I with 10. SO, if we don’t put a decrement of i inside the loop, the value of i will never be changed and this can cause an infinite loop and ultimately a shutdown of JVM due to low memory space.

So, while writing the while, we must be careful that it shouldn’t create an infinite loop.


Fortify your career and establish your future. Udemy online courses from ₹ 432 for a limited time. Next > < Prev

Scroll to Top