Udemy logo

javawhileloopSo you’ve just started learning Java, you’ve built your first Hello World program, and you’re feeling like a pro. But if you want your programs to do more and be more, you have to learn how to use loops.

There are three kinds of loop statements in Java, each with their own benefits – the while loop, the do-while loop, and the for loop. Loop mechanisms are useful for repeatedly executing blocks of code while a boolean condition remains true, a process that has a vast amount of applications for all types of software programming.

To understand the distinct uses of each loop statement, let’s take a look at the simple while loop. If you want a more in-depth, beginner friendly guide to learning Java, check out this tutorial for Java programming basics.

Syntax of the While Loop

The syntax of a while loop is as follows:

while(BooleanExpressionHere)
{
	YourStatementHere
}

The while statement will evaluate the boolean expression within the parentheses, and continue to execute the statement(s) within the curly braces as long as the expression is true.

This is the most important characteristic to note. The entirety of the loop body will be skipped over if the expression evaluated in the beginning is not true.

Keep this in mind for later when we examine the do-while loop. For now, let’s check out the while loop in action.

Example of a While loop

Let’s say you want to create a program that will count from 1 to 10, using a while loop.

public class WhileLoopExample
{
    public static void main(String args[])
    {
		int num = 0;
		System.out.println("Let's count to 10!");
		while(num < 10)
		{
			num = num + 1;
			System.out.println("Number: " + num);
		}
		System.out.println("We have counted to 10! Hurray! ");
	}
}

This is what your program will look like, and this is what it will return:

Let’s count to 10!
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10
We have counted to 10! Hurray!

What’s Going on Here?

Before we even open the loop, we have to set a condition for its boolean to evaluate. Because we want to count to 10, we create an int – named num in this example – and set its initial value to 0. We then have the program print the string, “Let’s count to 10!”

int num = 0;
System.out.println("Let's count to 10!");

From here, we open our while loop using the syntax we talked about before. Our goal is to increase the value of num to 10, one number at a time, before closing the loop. To do this, we set our boolean expression to num < 10. As long as the value of num is less than 10, it will continue executing the statements within the loop.

Those statements are num = num + 1, and a string that prints the word “Number:” followed by the current value of num after each execution.

while(num < 10)
{
	num = num + 1;
	System.out.println("Number: " + num);
}

What the program is doing is repeatedly checking the current value of num, adding 1, and printing its new value, before starting the process over again, and finally ending once the value of num is 10.

Once the loop is closed, it moves on to the next statement, which is a string that reads, “We have counted to 10! Hurray!” The program moves onto this next line because the boolean expression in the while loop above is no longer true, and so the while loop has closed.

Some While Loops Never Run

It’s possible for the loop body to never run at all, if the conditions are so that the boolean was either never true, or instantly untrue.

For instance, if the initial value of num is 0 and our boolean expression is num > 10, instead of num < 10, it is already false from the start, because 0 will never be greater than 10.

public class WhileLoopExample
{
    public static void main(String args[])
	{
		int num = 0;
		System.out.println("Let's count to 10!");
		while(num > 10)
		{
			num = num + 1;
			System.out.println("Number: " + num);
		}
		System.out.println("We have counted to 10! Hurray! ");
	}
}

Our while loop will evalute the boolean expression, num > 10, find that it is untrue, and print:

Let's count to 10!
We have counted to 10! Hurray!

The Do-While Loop

The syntax of a do-while loop is very similar to the while loop, with one significant difference – the boolean expression is located at the end of the loop, rather than at the beginning. This means the statements in the loop body will execute one time, before the boolean expression is evaluated.

public class DoWhileLoopExample {
   public static void main(String args[]){
      int num = 0;
      do{
         System.out.println("Number: " + num );
         num = num + 1;
      }while( num < 10 );
   }
}

What this returns is:

Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9

The main noticeable difference between what our first while loop returned and what this do-while loop returns is that our do-while loop counts from 0. This is because our do-while statement prints the initial value of num once before adding to it, evaluating the boolean, and then starting over.

This is also why it stops at 9, instead of 10, like our first while loop – once the value of num is 9 at the beginning of the loop, the statement num =  num + 1 makes it 10, rendering the boolean expression num < 10 untrue, thus closing the loop before it can print the next value.

You can read a more in-depth guide on how do-while loops work here.

Getting Stuck in an Infinite Loop

One of the most common errors you can run into working with while loops is the dreaded infinite loop. You risk getting trapped in an infinite while loop if the statements within the loop body never render the boolean eventually untrue. Let’s return to our first example.

Before, our statement num = num + 1 continually increased the value of num until it was no longer less than 10, rendering our boolean expression num < 10 untrue, and closing the loop – great success!

However, what if we had accidentally written num = num – 1 within the while loop?

public class WhileLoopExample
{
    public static void main(String args[])
	{
		int num = 0;
		System.out.println("Let's count to 10!");
		while(num < 10)
		{
			num = num - 1;
			System.out.println("Number: " + num);
		}
		System.out.println("We have counted to 10! Hurray! ");
	}
}

This would continue subtracting 1 from num, down into the negative numbers, keeping its value less than 10, forever. This is an infinite loop because our boolean will always remain true, meaning our program will continue to run it with no end in sight, unless we fix it.

This has been a basic tutorial on while loops in Java to help you get started. If you’re starting to envision yourself in a long and fruitful career coding in Java, check out this guide to Java-based interviews and their most common questions. If you still have a lot to learn, dive in with the ultimate Java tutorial for beginners.

Page Last Updated: December 2013

Top courses in Java

Java for Beginners
Navin Reddy
4.5 (1,860)
Java Interview Help
Bharath Thippireddy
4.4 (1,637)
Complete Java SE 8 Developer Bootcamp - OCA Prep Included
Intertech Training, Jeff Jensen
4.6 (9,697)
Modern Java - Learn Java 8 Features By coding it
Pragmatic Code School
4.5 (11,371)
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.5 (4,092)
Bestseller
Learn Selenium with Java, Cucumber & Frameworks
Pavan Kumar
4.6 (8,451)
Bestseller

More Java Courses

Java students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo