⬅ Previous Topic
Java For-Each LoopNext Topic ⮕
Java Do-While Loop⬅ Previous Topic
Java For-Each LoopNext Topic ⮕
Java Do-While LoopIn 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.
while
Loopwhile (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.
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
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.
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.
while
Loop to Iterate over an Arraypublic 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
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...
while
Loop?=
instead of ==
for comparison=
instead of ==
in a while loop condition can lead to unintended behavior.int[] nums = {10, 20, 30, 40, 50};
int index = 0;
while (index < nums.length) {
System.out.println("Element at index " + index + ": " + nums[index]);
index++;
}
⬅ Previous Topic
Java For-Each LoopNext Topic ⮕
Java Do-While LoopYou 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.