If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, the while
loop allows you to repeatedly execute a block of code as long as a specified condition is true. The loop will continue to execute until the condition becomes false. The basic syntax of the while
loop is as follows:
javaCopy code
while (condition) {
// Code to be executed repeatedly as long as the condition is true
}
Here's an example of using a while
loop to print numbers from 1 to 5:
javaCopy code
public class WhileLoopExample {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Number: " + count);
count++;
}
}
}
Output:
javascriptCopy code
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
In the example above, we initialize a variable count
to 1. The while
loop continues to execute as long as the condition count <= 5
is true. Inside the loop, we print the value of count
and then increment it using count++
. The loop will stop when the value of count
becomes 6 (which is not less than or equal to 5), and the loop exits.
It's important to be cautious when using while
loops to avoid infinite loops. An infinite loop occurs when the condition is always true, and the loop never terminates. To prevent this, ensure that the condition will eventually become false during the execution of the loop.
Comments: 0