Java while Loop
Description
The while
loop repeats a statement or block while its controlling
condition
is true
.
Syntax
Here is its general form:
while(condition) {
// body of loop
}
Note
- The
condition
can be anyBoolean
expression. - The body of the loop will be executed as long as the conditional
condition
istrue
. - The curly braces are unnecessary if only a single statement is being repeated.
Example
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;//from w w w . jav a2s . c o m
while (n > 0) {
System.out.println("n:" + n);
n--;
}
}
}
When you run this program, you will get the following result:
Example 2
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");
}/* w w w. j ava 2 s.co m*/
System.out.println("You are here");
}
}
The output:
Example 3
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;//from w ww .j a v a 2s . c o m
i = 10;
j = 20;
// find midpoint between i and j
while (++i < --j)
;
System.out.println("Midpoint is " + i);
}
}
The while
loop in the code above has no loop body and i
and
j
are calculated in the while loop condition statement.
It generates the following output: