The while loop in Java is used to repeatedly execute a block of code as long as the specified condition evaluates to true. It is commonly used when the number of iterations is not known in advance, and you want the loop to continue based on a condition.
Syntax:
while (condition) {
// Code to be executed
}
Important Points:
1. Condition: The loop checks the condition before executing the block of code. If the condition is false, the loop will terminate.
2. Infinite Loop: If the condition always evaluates to true, the loop will run indefinitely unless explicitly broken.
3. Use Case: Best for scenarios where you don’t know the exact number of iterations beforehand.
Example:
public class Main {
public static void main(String[] args) {
int count = 1;
while (count <= 4) {
System.out.println("Count is: " + count);
count++;
}
}
}
Output:
Count is: 1Count is: 2
Count is: 3
Count is: 4
Example 2: How to break the Loop
public class Main {
public static void main(String[] args) {
int count = 1;
while (true) { // Infinite loop
System.out.println("Count is: " + count);
count++;
if (count > 2) {
break; // Exit the loop
}
}
}
}
Output:
Count is: 1Count is: 2
Example 3: How to use continue in While loop?
public class Main {
public static void main(String[] args) {
int count = 0;
while (count < 5) {
count++;
if (count == 2) {
continue; // Skip the rest of the loop body for this iteration
}
System.out.println("Count is: " + count);
}
}
}
Output:
Count is: 1Count is: 3
Count is: 4
Count is: 5