Introduction to While Loop
The while loop is good for scenarios where you don't know how many times a block or statement should repeat, but you want to continue looping as long as some condition is true. Unlike the for loop, the while loop has no initialization or increment expressions.
Syntax
while (boolean-expression) {
// do stuff
statements(s)
}
The while statement evaluates boolean-expression, which must return a boolean value i.e. true or false. If the boolean-expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the boolean-expression on each iteration and executing its block until the boolean-expression evaluates to false.
Example
1. /**
2. * @(#)WhileLoopDemo.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/11
7. */
8.
9. public class WhileLoopDemo {
10.
11. /**
12. * Creates a new instance of <code>WhileLoopDemo</code>.
13. */
14. public WhileLoopDemo() {
15. }
16.
17. /**
18. * @param args the command line arguments
19. */
20. public static void main(String[] args) {
21. // TODO code application logic here
22.
23. int count = 1;
24. while (count < 6) {
25. System.out.println("Count is: " + count);
26. count++;
27. }
28.
29. }
30. }
Output
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
