Java While Loop

As we are discussed in previous file, java while loop is used to repeat the part of the program many times. If the number of repetition is not fixed, then while loop is use.

Syntax

while (condition)

{

statements (s)

}

Flowchart
Java while Loop

In above flowchart shows, firstly, condition is evaluated and if condition is true then statement in while loop is executed. If condition is false,then it comes to out of the loop and go to next statement.

Example

public class whileLoopExample{

public static void main(String[]args){

int i=1;

while(i<=15){

System.out.println(i);

i++;

}

}

}

Output

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

Infinitive While Loop

In while loop if we pass true it will be infinitive while loop.

Syntax

while (true){

statement(s);

}

Example

class WhileInfinitiveExample2 {

public static void main(String[] args) {

while(true){

System.out.println(“infinitive while loop”);

}

}

}

Output

infinitive while loop

infinitive while loop

infinitive while loop

infinitive while loop

infinitive while loop

ctrl+c

Ctrl+c is use to exit the program

Copyright 1999- Ducat Creative, All rights reserved.