Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java While Loop
Syntax, Flow & Examples



In Java, a while loop is used to repeat a block of code as long as a given condition remains true. It offers flexibility and control, especially when the number of iterations isn't known beforehand.

Syntax of Java while Loop

while (condition) {
    // code block to execute
}

The loop checks the condition before every iteration. If the condition evaluates to true, the code block executes. Once the condition becomes false, the loop stops running.

Simple Example: Counting from 1 to 5

public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println("Count: " + i);
            i++;
        }
    }
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Explanation

Here, the loop starts with i = 1. The condition i <= 5 is checked before each iteration. As long as this is true, it prints the current value of i and increments it. When i becomes 6, the loop terminates.

Important: Infinite While Loop

If the condition never turns false, the loop keeps running indefinitely. This is called an infinite loop.

while (true) {
    System.out.println("This loop runs forever!");
}

Be cautious with infinite loops. They're useful in some scenarios like real-time systems or game loops, but can also crash your program if misused.

Using while Loop to Iterate over an Array

public class ArrayWhileLoop {
    public static void main(String[] args) {
        int[] nums = {10, 20, 30, 40, 50};
        int index = 0;
        
        while (index < nums.length) {
            System.out.println("Element at index " + index + ": " + nums[index]);
            index++;
        }
    }
}
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Use Case: Validate User Input

The while loop is ideal when waiting for a correct user input:

import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = "";

        while (!input.equals("yes")) {
            System.out.print("Type 'yes' to continue: ");
            input = scanner.nextLine();
        }

        System.out.println("Great! Moving forward...");
    }
}
Type 'yes' to continue: no
Type 'yes' to continue: maybe
Type 'yes' to continue: yes
Great! Moving forward...

When Should You Use a while Loop?

Common Mistakes to Avoid

QUIZ

Question 1:What is the correct syntax for a Java while loop?

Question 2:In Java, a while loop executes at least once before checking the condition.

Question 3:Which of the following are valid use cases for a while loop in Java?

Question 4:What happens if the loop condition never becomes false?

Question 5:Using = instead of == in a while loop condition can lead to unintended behavior.

Question 6:Which of the following output lines would result from executing the given code?
int[] nums = {10, 20, 30, 40, 50};
int index = 0;
while (index < nums.length) {
    System.out.println("Element at index " + index + ": " + nums[index]);
    index++;
}



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M