While Loop

  • Eclipse: Oxygen
  • Java: 1.8

While loop in Java is a structure which 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, 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

1

2

3

4

5

6

7

8

9

10

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

Infinite loop

Infinite loop

Infinite loop

Infinite loop

Infinite loop

Infinite loop

Infinite loop

Infinite loop

Break

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

Demonstrate break statement

Output

Infinite loop

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 time 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

 

 

 


VIEW COURSES

Buy me a coffee!

 

PayTM QR (INDIA)

  • Get video tutorials
  • Project files set
  • Get Certified

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu