Java while Loop

htt‮ww//:sp‬w.theitroad.com

In Java, the while loop is used to execute a block of code repeatedly as long as a given condition is true. It's a type of loop that allows you to specify a condition that must be true for the loop to continue.

Here is the basic syntax of the while loop in Java:

while (condition) {
    // code to execute for each iteration
}

The while loop has one part:

  • Condition: This is the test that is performed at the beginning of each iteration. The loop continues as long as this condition is true.

Here is an example that uses the while loop to print the numbers from 1 to 10:

int i = 1;
while (i <= 10) {
    System.out.println(i);
    i++;
}

In this example, the loop starts with i being initialized to 1. The loop continues as long as i is less than or equal to 10. The loop prints the value of i for each iteration, and increments the value of i by 1 at the end of each iteration, resulting in the numbers 1 to 10 being printed to the console.

You can also use the while loop to read input from the user or to wait for a specific condition to be true. Here is an example that uses the while loop to read integers from the user until the user enters a negative number:

Scanner scanner = new Scanner(System.in);

int number = 0;
while (number >= 0) {
    System.out.print("Enter a number (negative to quit): ");
    number = scanner.nextInt();
    System.out.println("You entered: " + number);
}

In this example, the loop reads integers from the user until the user enters a negative number. The loop checks whether the entered number is non-negative, and if it is, it prints the entered number to the console. If the user enters a negative number, the loop terminates and the program ends.