A 4-minute guide to Java loops

Whether you use a while loop, a do while loop, or an infinite loop, understanding how loops work is vital to Java programming.
No readers like this yet.
arrows cycle symbol for failing faster

Opensource.com

A while loop performs a set of tasks for as long as some predefined condition is true. This is considered a control structure that directs the flow of a program. It's a way for you to tell your code what to do by defining a condition that it can test, and take action based on what it finds. The two kinds of while loops in Java are while and do while.

Java while loop

A while loop is meant to iterate over data until some condition is satisfied. To create a while loop, you provide a condition that can be tested, followed by the code you want to run. Java has several built-in test functions, the simplest of which are mathematical operators (<, >, ==, and so on):

package com.opensource.example;

public class Example {
  public static void main(String[] args) {

  int count = 0;
  while (count < 5) {
    System.out.printf("%d ", count);
    count++;
    }
  }
}

In this simple example, the condition is that the variable count is less than 5. Because count is instantiated at 0, and then incremented by 1 in the code within the while loop, the program iterates a total of 5 times:

$ java ./while.java
0 1 2 3 4

Before it can iterate a sixth time, the condition is no longer true, so the loop ends.

The conditional statement for a while loop is vital. Getting it wrong could mean that your loop never executes. For instance, suppose you had set count == 5 as the condition:

  while (count == 5) {
    System.out.printf("%d ", count);
    count++;

When you run the code, it builds and runs successfully, but nothing happens:

$ java ./while.java
$

The loop has been skipped because count was set to 0, and it's still 0 at the moment the while loop is first encountered. The loop never has a reason to start and count is never incremented.

The reverse of this is when a condition starts as true and can never be false, this results in an infinite loop.

Java do while loop

Similar to the while loop, a do while loop tests for the conditional at the end, not the beginning, of each iteration. With this, the code in your loop runs at least once because there's no gateway to entry, only a gateway to exit:

package com.opensource.example;

public class Example {
  public static void main(String[] args) {

  int count = 9;
  do {
      System.out.printf("%d ", count);
      count++;
    } while(count == 5);
  }
}

In this sample code, count is set to 9. The condition for the loop to repeat is that count is equal to 5. But 9 isn't equal to 5. That check isn't performed until the end of the first iteration, though:

$ java ./do.java
9

Java infinite loops

An infinite loop, as its name suggests, never ends. Sometimes they're created by mistake, but an infinite loop does have a valid use case. Sometimes you want a process to continue indefinitely (that's functionally infinite because you can't guarantee when you need it to stop), and so you might set your condition to something impossible to meet.

Suppose you've written an application that counts the number of zombies remaining in your neighborhood during a zombie apocalypse. To simulate uncertainty over how many loops are required to get to 0 zombies, my demo code retrieves a timestamp from the operating system and sets the value of the counter (c) to some number derived from that timestamp. Because this is a simple example and you don't really want to get trapped in an infinite loop, this code counts down to zero and uses the break function to force the loop to end:

package com.opensource.example;

public class Example {
  public static void main(String[] args) {

  long myTime = System.currentTimeMillis();

  int c;

  if ( myTime%2 == 0 ) {
      c = 128;
  } else {
      c = 1024;
  }

  while(true) {
    System.out.printf("%d Zombies\n", c);

    // break for convenience
    if ( c <= 0 ) { break; }
    c--;
    }
  }
}

You may have to run it a few times to trigger a different total number of zombies, but sometimes your program iterates 128 times and other times 1,024 times:

$ java ./zcount.java
1024 Zombies
1023 Zombies
[...]
0 Zombies

Can you tell why the loops end at 0 and not at -1?

Java loops

Loops give you control over the flow of your program's execution. Iteration is common in programming, and whether you use a while loop, a do while loop, or an infinite loop, understanding how loops work is vital.

Tags
Seth Kenlon
Seth Kenlon is a UNIX geek, free culture advocate, independent multimedia artist, and D&D nerd. He has worked in the film and computing industry, often at the same time.

Comments are closed.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.