FAQ: example of a Java while loop

By Alvin J. Alexander, devdaily.com

Question: Can you show me an example of a Java while loop?

Sure, here's one example:

package com.devdaily.javasamples;

public class WhileTest
{
  public static void main(String[] args)
  {
    int i = 0;
    while (i < 5)
    {
      System.out.println("i = " + i);
      i++;
    }
  }

}

This example prints out the value of the variable i until i gets to 5, at which point the loop stops.

Note that there are several other ways to increment the variable i, but I've shown it as a separate line as it's the most obvious way.


devdaily logo