‹‹ Previous
Next ››
Java 'While' Loop
- The 'while' loop is used for repeating a set of instructions.
- It is used to repeat the statements until a condition becomes false.
- In other words, it is used to repeat the statements till a condition is true.
- Number of repetitions are not fix in the 'while' loop. However, number of repetitions are fix in 'for' loop
- Number of repetitions depend on the condition which is used in the 'while' loop.
- The 'while' loop is used when number of repetitions are not known in advance and it depends on condition given in the 'while' loop.
Example
Program: Display the message "Dear Learner", if user press 1. Otherwise, the 'while' loop terminates.
import java.util.*;
class DispMessg {
public static void main(String args[])
{
Scanner userinput = new Scanner(System.in);
int choice = 1;
while(choice == 1)
{
System.out.println("Dear Learner");
System.out.println("Do you want to display the message more (Press 1) :");
choice = userinput.nextInt();
}
}
}
Explanation of the program
- In this program, Frequency of displaying the message "Dear Learner" depends on user input.
- if user gives input 1 then message "Dear Learner" will be displayed.
- if user gives input other than 1, then 'while' loop condition will be false and the loop will terminate.
Output of the program
Dear Learner
Do you want to display the message more (Press 1) :
1
Dear Learner
Do you want to display the message more (Press 1) :
1
Dear Learner
Do you want to display the message more (Press 1) :
1
Dear Learner
Do you want to display the message more (Press 1) :
1
Dear Learner
Do you want to display the message more (Press 1) :
1
Dear Learner
Do you want to display the message more (Press 1) :
0
‹‹ Previous
Next ››