05.03. While Loop

While Loop

  • Eclipse: Oxygen
  • Java: 1.8

While loop in Java is a structure that executes a statement of code multiple times until the boolean expression is false.

In While loop, boolean expression is evaluated before the execution of code. If the boolean expression is evaluated as true, then only the execution of code starts, and if the expression is evaluated as false, the block of code inside while loop will not be executed.

Structure

 

Syntax

In this example, initialize the loop counter “i” with value 1. In the while condition, check whether it is less than or equal to 10 (i=<10), it will print the number in the new line and i++ increment the counter by1. It will print the number repeatedly unless counter becomes greater than 10.

Output

Infinite loop

In the following example, the boolean expression, that is evaluated before each loop iteration is never modified, so the expression (true) will always evaluate true. The result is, the loop will never end. It is known as an infinite loop.

Output

Break

In Java programming, the break is used in terminating the loop immediately after it is encountered.

Demonstrate break statement

Output

Difference between for loop and while loop

  • For loop is used when we know the number of iterations. For example when we are sure that how many times we need to execute a loop.
  • While loop is used when we are unsure about the number of iteration and want to loop while some condition is true. It will loop that block until the condition is false.

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments