The while statement has the following syntax.
while (booleanExpression) { statement (s) }
As an example of the while statement, the following code prints integer numbers that are less than three.
public class MainClass { public static void main(String[] args) { int i = 0; while (i < 3) { System.out.println(i); i++; } } }
To produce three beeps with an interval of 500 milliseconds, use this code:
public class MainClass { public static void main(String[] args) { int j = 0; while (j < 3) { java.awt.Toolkit.getDefaultToolkit().beep(); try { Thread.currentThread().sleep(500); } catch (Exception e) { } j++; } } }
Sometimes, you use an expression that always evaluates to true (such as the boolean literal true) but relies on the break statement to escape from the loop.
public class MainClass { public static void main(String[] args) { int k = 0; while (true) { System.out.println(k); k++; if (k > 2) { break; } } } }
4.4.While Loop | ||||
4.4.1. | The while Statement | |||
4.4.2. | Using the while loop to calculate sum | |||
4.4.3. | While loop with double value | |||
4.4.4. | Java's 'labeled while' loop |