Java While Loop
Repeating code execution in Java
🔄 What is Java While Loop?
Java While Loop repeats a block of code as long as a condition remains true. It's perfect for situations where you don't know exactly how many times to repeat something.
// Simple while loop
int count = 1;
while (count <= 3) {
System.out.println("Count: " + count);
count++; // Increment to avoid infinite loop
}
System.out.println("Loop finished!");
Output:
Count: 1
Count: 2
Count: 3
Loop finished!
Types of While Loops
While Loop
Check condition before executing
while (condition) {
// code to repeat
}
Do-While Loop
Execute first, then check condition
do {
// code to repeat
} while (condition);
Infinite Loop
Loop that never ends (avoid this!)
while (true) {
// This runs forever!
// Use break to exit
}
Nested Loop
Loop inside another loop
while (outer_condition) {
while (inner_condition) {
// nested code
}
}
🔹 Basic While Loop
Counting and repeating actions with while loop:
public class WhileLoopExample {
public static void main(String[] args) {
// Counting from 1 to 5
int i = 1;
System.out.println("Counting up:");
while (i <= 5) {
System.out.println("Number: " + i);
i++; // Same as i = i + 1
}
// Counting down
int j = 5;
System.out.println("\nCountdown:");
while (j > 0) {
System.out.println(j + "...");
j--;
}
System.out.println("Blast off!");
}
}
Output:
Counting up:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Countdown:
5...
4...
3...
2...
1...
Blast off!
🔹 Do-While Loop
Execute code at least once, then check condition:
public class DoWhileExample {
public static void main(String[] args) {
int number = 10;
// Regular while loop - may not execute at all
System.out.println("Regular while loop:");
while (number < 5) {
System.out.println("This won't print");
number++;
}
// Do-while loop - executes at least once
System.out.println("Do-while loop:");
do {
System.out.println("This will print once: " + number);
number++;
} while (number < 5);
// Practical example - menu system
int choice;
do {
System.out.println("\n--- Menu ---");
System.out.println("1. Option A");
System.out.println("2. Option B");
System.out.println("0. Exit");
choice = 0; // Simulating user input
System.out.println("Selected: " + choice);
} while (choice != 0);
}
}
Output:
Regular while loop:
Do-while loop:
This will print once: 10
--- Menu ---
1. Option A
2. Option B
0. Exit
Selected: 0
🔹 Loop Control Statements
Using break and continue to control loop execution:
public class LoopControl {
public static void main(String[] args) {
// Using break to exit loop early
System.out.println("Using break:");
int i = 1;
while (i <= 10) {
if (i == 6) {
System.out.println("Breaking at " + i);
break; // Exit the loop
}
System.out.println("i = " + i);
i++;
}
// Using continue to skip iterations
System.out.println("\nUsing continue (skip even numbers):");
int j = 0;
while (j < 8) {
j++;
if (j % 2 == 0) {
continue; // Skip rest of this iteration
}
System.out.println("Odd number: " + j);
}
}
}
Output:
Using break:
i = 1
i = 2
i = 3
i = 4
i = 5
Breaking at 6
Using continue (skip even numbers):
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
🔹 Practical While Loop Examples
Real-world applications of while loops:
public class PracticalExamples {
public static void main(String[] args) {
// Example 1: Sum of numbers
int sum = 0;
int num = 1;
while (num <= 5) {
sum += num; // Add num to sum
num++;
}
System.out.println("Sum of 1 to 5: " + sum);
// Example 2: Finding digits in a number
int number = 12345;
int digitCount = 0;
int temp = number;
while (temp > 0) {
temp = temp / 10; // Remove last digit
digitCount++;
}
System.out.println("Number of digits in " + number + ": " + digitCount);
// Example 3: Password attempts
String correctPassword = "java123";
String userInput = "wrong"; // Simulating user input
int attempts = 0;
int maxAttempts = 3;
while (!userInput.equals(correctPassword) && attempts < maxAttempts) {
attempts++;
System.out.println("Attempt " + attempts + ": Password incorrect");
if (attempts < maxAttempts) {
userInput = (attempts == 2) ? "java123" : "wrong"; // Simulate correct on 3rd try
}
}
if (userInput.equals(correctPassword)) {
System.out.println("Access granted!");
} else {
System.out.println("Access denied. Too many attempts.");
}
}
}
Output:
Sum of 1 to 5: 15
Number of digits in 12345: 5
Attempt 1: Password incorrect
Attempt 2: Password incorrect
Access granted!