Loops are used to repeat a block of code as long as a specified condition is true.
The for loop is used when you know in advance how many times you want to execute a statement or a block of statements.
Syntax:
for (initialization; condition; update) {
// Code to execute
}
xxxxxxxxxxpublic class ForLoopExample { public static void main(String[] args) { for (int i = 0; i < 5; i++) { System.out.println("i = " + i); } }}i = 0
i = 1
i = 2
i = 3
i = 4The while loop repeats a block of code as long as a condition is true. It's useful when you don't know in advance how many times the loop should run.
Syntax:
while (condition) {
// Code to execute
}xxxxxxxxxxpublic class WhileLoopExample { public static void main(String[] args) { int i = 0; while (i < 5) { System.out.println("i = " + i); i++; } }}i = 0
i = 1
i = 2
i = 3
i = 4The do-while loop is similar to the while loop, but the condition is checked after the loop body is executed. This guarantees that the loop will run at least once.
Syntax:
do {
// Code to execute
} while (condition);
xxxxxxxxxxpublic class DoWhileExample { public static void main(String[] args) { int i = 0; do { System.out.println("i = " + i); i++; } while (i < 5); }}i = 0
i = 1
i = 2
i = 3
i = 4