In programming languages, loops are used to make a block of code run multiple times. In some cases, the number of repetitions depends on meeting certain conditions. In these cases, using the while loop is a practical solution
Java While Loops
The while loop is the loop used to run a block of code as long as certain conditions are met.
while (boolean condition) { // if condition is true, then execute this code block }
Example 1: Create a while loop to print numbers from 1 to 10.
int counter=1; while (counter<=10) { System.out.print(counter+" "); counter++; }
Output is: 1 2 3 4 5 6 7 8 9 10
Example 2: Create an infinite loop with the while loop
while (true) System.out.print("This is an infinite loop");
or
while (true) { System.out.print("This is an infinite loop"); }
Unlike while loop, do-while loop will execute the code block once without checkink the boolean condition term. Following loops will be repeated as long as the condition is not false.
do { // code block } while (boolean condition);
Example 3: Create a do-while loop that continues to request numbers as long as the user continues to enter a positive number.
Scanner input = new Scanner(System.in); int number; do { System.out.println("Please write a number"); number = input.nextInt(); } while (number > 0);
Output:
Please write a number > 6 Please write a number > 10 Please write a number > 200 Please write a number > -1