A loop is a control structure that causes a statement or group of statements to repeat.
Java supports three looping structures:
- while
- do...while
- for
The while statement has two parts:
- a boolean expression (tests whether the condition is true or false)
- a statement or block of statements that is repeated until the condition is true
Syntax
Here is the general format of the while loop:
while (BooleanExpression)
Statement;
Logic
How while loop works?
The Boolean Expression is tested, and if it is true, the Statement is executed. Then, the Boolean Expression is tested again. If it is true, the Statement is executed. This cycle repeats until the Boolean Expression is false.
Example (WhileLoop.java)
public class WhileLoop
{
public static void main(String[] args)
{
int number = 1;
while (number <= 5)
{
System.out.println("Hello");
number++;
}
System.out.println("That's all!");
}
}
Output
Hello
Hello
Hello
Hello
Hello
That's all!
No comments:
Post a Comment