• Skip to main content
  • Skip to after header navigation
  • Skip to site footer

Free-Mail

  • Events
  • Images
    • Instagram Goodness
  • Music
  • News
  • Software

A 4-minute guide to Java loops

A 4-minute guide to Java loops: A 4-minute guide to Java loops sethkenlon Sat, 01/14/2023 – 03:00

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

More on Java
What is enterprise Java programming?
An open source alternative to Oracle JDK
Java cheat sheet
Red Hat build of OpenJDK
Free online course: Developing cloud-native applications with microservices
Fresh Java articles

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.

Whether you use a while loop, a do while loop, or an infinite loop, understanding how loops work is vital to Java programming.

arrows cycle symbol for failing faster
Image by:

Opensource.com

Java

What to read next
Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.
Register or Login to post a comment.

: Opensource.com sethkenlon

Supporting Open Source.

Have you tried: Visiting Port Elizabeth?

Share this:

  • Share on Facebook (Opens in new window) Facebook
  • Share on X (Opens in new window) X
  • Share on Pinterest (Opens in new window) Pinterest
  • Email a link to a friend (Opens in new window) Email
  • More
  • Share on Tumblr (Opens in new window) Tumblr
  • Print (Opens in new window) Print
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on Reddit (Opens in new window) Reddit
Published on 14 January 2023 by Alan Category: SoftwareTag: 4minute, Guide, java, Loops

Marina Pacowski – Meadowlark Music Festival

Marina Pacowski – Meadowlark Music Festival – a Music interest event taking place on …

Read moreMarina Pacowski – Meadowlark Music Festival

Cool Cape Town – Statue of Dias image

A cool Cape Town image: Cape Town – Statue of Dias Image by JingKe888 DSCF0273 Image …

Read moreCool Cape Town – Statue of Dias image

Nice South african Food Store: Popes Quay – Cork City photo

A nice South African City image: South african Food Store: Popes Quay – Cork City Image by …

Read moreNice South african Food Store: Popes Quay – Cork City photo

About Alan

Previous Post:South Korea to ban bear farming, but what to do about hundreds of captive animals that remain?
Next Post:Why cholera continues to threaten many African countries

Reach Trust

Reach Trust is a holding trust for a number of companies within the Stratlec Group.

Copyright © 2026 · Free-Mail · All Rights Reserved · Powered by Straton Electrical

Back to top