Introduce Java While Loop and give examples
A while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The loop continues to execute as long as the condition evaluates to true
. If the condition is false
at the start, the code inside the loop will not execute at all.
while (condition) {
// Code to be executed
}
true
, the code inside the loop is executed.false
, the loop terminates, and control passes to the statement following the loop.Here’s a simple example that prints numbers from 1 to 5:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1; // Initialize the counter
while (i <= 5) { // Condition
System.out.println(i); // Print the current value of i
i++; // Increment the counter
}
}
}
Output:
1
2
3
4
5
In this example, we will use a while loop to calculate the sum of numbers from 1 to 10.
public class SumWhileLoop {
public static void main(String[] args) {
int sum = 0; // Initialize sum
int i = 1; // Initialize counter
while (i <= 10) { // Condition
sum += i; // Add i to sum
i++; // Increment counter
}
System.out.println("The sum of numbers from 1 to 10 is: " + sum);
}
}
Output:
The sum of numbers from 1 to 10 is: 55
Here’s an example of an infinite loop that can be terminated using a break
statement:
public class InfiniteLoopExample {
public static void main(String[] args) {
int count = 0;
while (true) { // Infinite loop
System.out.println("Count: " + count);
count++;
if (count >= 5) { // Condition to break the loop
break; // Exit the loop
}
}
}
}
Output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
The while loop is a fundamental control structure in Java that allows for repeated execution of a block of code as long as a specified condition is true. It is essential to manage the loop's condition carefully to avoid infinite loops and ensure that the loop will eventually terminate.