While loop

While loop in JAVA

Syntax

while(condition){
//code to be executed
}

Program

 
public class while_loop
{
public static void main(String args[])
{
int i = 1;
while(i <= 10)
{
System.out.println(i);
i++;
}
}
}

Output

 
1
2
3
4
5
6
7
8
9
10

Explanation

The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.
  • While loop starts with the checking of condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason it is also called Entry control loop.
  • Once the condition is evaluated to true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.
  • When the condition becomes false, the loop terminates which marks the end of its life cycle.

Infinite while loop

Syntax

while(true){
//code to be executed
}

Program

 
public class infinite_while
{
public static void main(String args[])
{
while(true)
{
System.out.println("Infinite while loop");
}
}
}

Output

 
Infinite while loop
Infinite while loop
Infinite while loop
Infinite while loop
Infinite while loop
Infinite while loop
Infinite while loop
Infinite while loop

Explanation

  • If you pass true in the while loop, it will be infinitive while loop.
  • Here, condition is always true so program runs continuously. You have to press ctrl+c to stop the program.
  • Remember true and false are keywords in Java.

Comments

Popular posts from this blog

System.Environment

System.Console

Datatype and keyword