Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0052 while loop

The while loop repeats a statement or block while its controlling expression is true. Here is its general form: while(condition) { // body of loop } The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. The curly braces are unnecessary if only a single statement is being repeated. Here is a while loop that counts down from 10, printing exactly ten lines of "tick": public class Main { public static void main(String args[]) { int n = 10; while (n > 0) { System.out.println("n:" + n); n--; } } } When you run this program, you will get the following result: n:10 n:9 n:8 n:7 n:6 n:5 n:4 n:3 n:2 n:1 The body of the while loop will not execute if the condition is false. For example, in the following fragment, the call to println() is never executed: public class Main { public static void main(String[] argv) { int a = 10, b = 20; while (a > b) { System.out.println("This will not be displayed"); } System.out.println("You are here"); } } The output: You are here The body of the while can be empty. For example, consider the following program: public class Main { public static void main(String args[]) { int i, j; i = 10; j = 20; // find midpoint between i and j while (++i < --j) ; System.out.println("Midpoint is " + i); } } It generates the following output: Midpoint is 15