Loops in Java – While Loop
package practice;
public class WhileLoop {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
Explanation
Loops are used in programming to repeat a block of code multiple times. Instead of writing the same line again and again, you can use a loop to automate repetition, which makes code shorter, cleaner, and more powerful.
How the while Loop Works:
int i = 0;→ Initializes the loop variable.while (i < 5)→ Checks the condition before executing the block.System.out.println(i);→ Prints the value ofi.i++;→ Increasesiby 1.This repeats until the condition
i < 5becomes false (i.e., wheni = 5).
Output –
0
1
2
3
4