Java While Loop
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java While Loop

Jeevadharshan

Java While Loop 

In Java, loops allow you to execute a block of code repeatedly while a specified condition remains true. They are essential for automating repetitive tasks, processing collections, and building efficient programs. 
 
Among Java’s loop constructs, the while loop is ideal when the number of iterations is not known in advance and depends on a runtime condition. 

What Is a While Loop in Java? 

The while loop repeatedly executes a block of code as long as its condition evaluates to true. 
 
Syntax 

while (condition) { 
    // code to execute repeatedly 

Key idea:
  • Condition checked before each iteration 
  • Loop stops when condition becomes false
Example 1: Printing Even Numbers  
 
This program prints all even numbers from 2 to 10 using a while loop. 
 
public class EvenNumberWhileLoop { 
    public static void main(String[] args) { 
        int number = 2; 
 
        while (number <= 10) { 
            System.out.println(number); 
            number += 2;  // increment by 2 
        } 
    } 

Output: 

10

Important: Update the Loop Variable 

A while loop must modify the variable used in its condition. Otherwise, the condition never changes and the loop runs forever (infinite loop). 
 
Example of an infinite loop (avoid this): 
 
int x = 1; 
 
while (x <= 5) { 
    System.out.println(x); 
    // missing x++ 
 
Example 2: Reverse Countdown Timer  
 
This program counts down from 5 to 1 and then displays a message. 
 
public class CountdownWhileLoop { 
    public static void main(String[] args) { 
        int seconds = 5; 
 
        while (seconds > 0) { 
            System.out.println("T-minus " + seconds); 
            seconds--; 
        } 
 
        System.out.println("Launch!"); 
    } 

Output: 

T-minus 5 
T-minus 4 
T-minus 3 
T-minus 2 
T-minus 1 
Launch!

While Loop with Initially False Condition 

If the condition is false the first time it’s checked, the loop body will not execute even once. 
 
Example 3: Condition False at Start 
 
public class WhileFalseConditionDemo { 
    public static void main(String[] args) { 
        int temperature = 35; 
 
        while (temperature < 30) { 
            System.out.println("Cooling system active"); 
            temperature--; 
        } 
 
        System.out.println("Temperature check complete"); 
    } 

Output: 

Temperature check complete  

Why “i” Is Common in Loops 

You’ll often see loop variables named i, j, or k. This convention comes from mathematics and stands for index or iterator. Short names are practical in simple counting loops, though descriptive names are better in real applications.

When to Use a While Loop

Use a while loop when:
  • The number of iterations is unknown 
  • Loop depends on a changing condition 
  • Waiting for user input or events 
  • Processing data until a limit is reached 
Examples: 
  • Reading file data until EOF 
  • Game loops 

Java do-while Loop 

The do-while loop in Java is a variation of the while loop that guarantees the loop body executes at least once, regardless of whether the condition is initially true or false. This makes it especially useful for scenarios such as menu-driven programs, input validation, and retry logic.  

What Is a do-while Loop in Java? 

A do-while loop executes its code block first and then evaluates the condition. If the condition 
remains true, the loop continues repeating. 
 
Syntax 
 
do { 
    // code to execute 
} while (condition);  

Important: 

The semicolon (;) after the while condition is required in Java syntax. 
 
Example 1: Menu Display  
 
This program displays a simple menu at least once and repeats until the user chooses to exit. 
 
import java.util.Scanner; 
 
public class MenuDoWhileExample { 
    public static void main(String[] args) { 
        Scanner scanner = new Scanner(System.in); 
        int choice; 
 
        do { 
            System.out.println("=== MAIN MENU ==="); 
            System.out.println("1. View Profile"); 
            System.out.println("2. Settings"); 
            System.out.println("3. Exit"); 
            System.out.print("Enter choice: "); 
 
            choice = scanner.nextInt(); 
 
            if (choice == 1) { 
                System.out.println("Opening profile..."); 
            } else if (choice == 2) { 
                System.out.println("Opening settings..."); 
            }

         } while (choice != 3); 
 
        System.out.println("Application closed."); 
        scanner.close(); 
    } 

Why do-while here? 

The menu must appear at least once before checking whether the user selected Exit. 
 
Example 2: Input Validation Loop 
 
This program repeatedly asks for a positive number until the user enters a valid value. 
 
import java.util.Scanner; 
 
public class PositiveNumberValidator { 
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        int number; 
 
        do { 
            System.out.print("Enter a positive number: "); 
            number = input.nextInt(); 
        } while (number <= 0); 
 
        System.out.println("Valid number entered: " + number); 
        input.close(); 
    } 
 
do-while with Initially False Condition 
 
Even if the condition is false at the start, the loop body still executes once. 
 
Example 3: Single Execution Demo 
 
public class DoWhileSingleRun { 
    public static void main(String[] args) { 
        int attempts = 5; 
 
        do { 
            System.out.println("Attempt recorded: " + attempts); 
            attempts++; 
        } while (attempts < 3); 
 
        System.out.println("Loop finished."); 
    } 
}  

Output: 

Attempt recorded: 5 
Loop finished. 
 
The condition attempts < 3 is false initially, but the loop runs once before evaluation.

When to Use a do-while Loop 

Use do-while when an action must occur at least once, such as: 
  • Displaying menus 
  • Reading user input 
  • Confirmation prompts 
  • Retry operations 
  • Game loops (first frame must render) 

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !