Simple Java While Loop Example
Java While Loop is used to iterate a program code for non-specified number of times.
Syntax:
Example:
Output:
Syntax:
while(condition)
{
//execute this code if condition is true
}
Example:
public class WhileLoop {
public static void main(String args[])
{
int num=1;
while (num<=9)
{
System.out.println("Number is "+num);
num++;
}
}
}
Output:
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
BUILD SUCCESSFUL (total time: 0 seconds)
Java Infinitive While Loop
If we replace the condition with boolean true,while loop becomes infinitive while loop.
Syntax:
while(true)
{
//execute this code here
}
Example:
public class InfinitiveLoop
{
public static void main(String args[])
{
while (true)
{
System.out.println("Infinitive Java While Loop");
}
}
}
Output:
Infinitive Java While Loop
Infinitive Java While Loop
Infinitive Java While Loop
Infinitive Java While Loop
Infinitive Java While Loop
Infinitive Java While Loop
Infinitive Java While Loop
Infinitive Java While Loop
Infinitive Java While LoopBUILD STOPPED (total time: 1 second)