Java while Loop

The while loop in Java is a control flow statement that allows you to repeat a block of code as long as a given condition is true.

The basic syntax is:

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

The condition is evaluated before each iteration. If the condition is true, the code inside the loop is executed. Once the condition becomes false, the loop terminates and program control continues after the loop.

Infinite while loop

An infinite while loop is a loop in Java that continues to run indefinitely because the loop condition always evaluates to true. This can occur if the condition is set to a constant true value, or if the condition never changes within the loop body.

Here's an example of an infinite while loop in Java:

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

It is important to note that infinite loops can cause the program to hang or crash, so it is important to ensure that the loop condition will eventually evaluate to false, otherwise the loop will never terminate.

To prevent infinite loops, a counter or a conditional statement that modifies the condition should be used within the loop.

Here are a few examples of while loops in Java:

  1. Printing numbers from 1 to 10:
int i = 1;
while (i <= 10) {
    System.out.println(i);
    i++;
}
  1. Reading input from the user until they enter a positive number:
import java.util.Scanner;

Scanner sc = new Scanner(System.in);
int number;

System.out.print("Enter a positive number: ");
number = sc.nextInt();

while (number <= 0) {
    System.out.print("Enter a positive number: ");
    number = sc.nextInt();
}
  1. Calculating the factorial of a number:
import java.util.Scanner;

Scanner sc = new Scanner(System.in);
int number, factorial = 1;

System.out.print("Enter a positive number: ");
number = sc.nextInt();

int i = 1;
while (i <= number) {
    factorial *= i;
    i++;
}

System.out.println("The factorial of " + number + " is " + factorial);