In Java several loops are available—each has its benefits. A while
-loop tends to be best when there is no simple exit condition.
With the while
-loop, a block of statements repeat infinitely—until the terminating condition (or a break
or return) is reached. With break
or return, we can exit the loop.
In this example, we control a loop based on both "i" and "z." This could be expressed with a for
-loop, but it might be less clear.
for
-loops are more often useful. But in cases where the loop termination is unknown, a while
-loop is better.public class Program { public static void main(String[] args) { int i = 0; int z = 10; // Loop with two variables. while (i < z) { i++; z--; // Display the values. System.out.println(i + "/" + z); } } }1/9 2/8 3/7 4/6 5/5
while-true
Break is often useful in while
-loops. But it can be used in any kind of loop. Here we show a while-true
loop—it would be infinite if there were no break
statement.
break
statement terminates the loop. No further iterations are run.while
-loop until it reaches a random number greater than 0.8.import java.lang.Math; public class Program { public static void main(String[] args) { // Loop infinitely. while (true) { // Get random number between 0 and 1. double value = Math.random(); System.out.println(value); // Break if greater than 0.8. if (value >= 0.8) { break; } } } }0.16129889659284657 0.0977987643977064 0.859556475501672
This loop is just like a while
-loop, except its condition is not checked before the first iteration is reached. So we must ensure the loop works with its initial value.
do-while
loop can make programs faster by reducing the number of checks done.public class Program { public static void main(String[] args) { int i = 0; // Loop while the variable is less than 3. // ... It is not checked on the first iteration. do { System.out.println(i); i++; } while (i < 3); } }0 1 2
This while
-loop uses several syntax forms. It uses a post-increment in the while
-loop condition. This means the test is done before the increment is done.
public class Program { public static void main(String[] args) { int index = 0; // Use post increment in while-loop expression. while (index++ < 10) { // Continue if even number. if ((index % 2) == 0) { continue; } System.out.println("Element: " + index); } } }Element: 1 Element: 3 Element: 5 Element: 7 Element: 9
Loops seem simple—but we find the most complex algorithms are based mainly on loops. It is important to clearly understand Java loops.