Java while Loop
In this chapter you will learn:
- What is Java while loop
- How to use the basic Java While Loop
- Note for Java while Loop
- Example - Java while loop
- Example - while condition
- Example - while loopbody
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 . j a v a 2s . c om
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 ww. j a va2 s .c o 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;// w w w . java 2 s . com
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:
Next chapter...
What you will learn in the next chapter:
- Why do we need Java do while loop
- Syntax for Java do while loop
- Example - How to use do-while statement
- How to create a simple help menu with while loop and switch statement