A Java for loop combines initialization, a condition, and an update. The body runs while the condition is true.
A simple example
Print the numbers 1 to 3
Start withStart at 1
Do thisVisit 1, 2, 3
Result1 → 2 → 3
Each pass prints one number on its own line. After 3 the loop has no more values to visit.Main.java
class Main {
public static void main(String[] args) throws Exception {
for (int n = 1; n <= 3; n++) {
System.out.println(n);
}
}
}
Output
1
2
3
Keep the printed bin numbers
Three supply bins contain 3, 0 and 5 items. Skip printing the empty middle bin but keep its position in the sequence. The last line must still refer to bin 3.
Example: #1 - Simple for Loop
Print the integers from 1 through 5 using a for loop.
Example: #2 - Iterate over an array or iterable using for Loop
Visit each array element and print its value.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int[] arr = new int[]{ 1,2,3,4,5};
for(int i : arr) {
System.out.println(i);
}
}
}
Output
1
2
3
4
5
Example: #3 - Iterate over an array with temporary variable using for Loop
Visit each array element and print its value.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int[] arr = new int[]{ 1,2,3,4,5};
for (int i = 0; i < arr.length; i++) {
int j = arr[i];
System.out.println(j);
}
}
}
Output
1
2
3
4
5
Java for Loop with break Statement
Use break to exit the loop immediately.
Example: #4 - for Loop with break Statement
Stop the loop after printing 3.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
for(int counter = 1; counter <= 5; counter++) {
System.out.println(counter);
// Terminate the execution once counter reached 3
if(counter == 3) {
break;
}
}
}
}
Output
1
2
3
Java while Loop with continue Statement
A continue skips to the update expression before the next condition check.
Example: #5 - for Loop with continue Statement
Skip the iteration for the counter value 3.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
for(int counter = 1; counter <= 5; counter++) {
// skips the iteration once counter reached 3
if(counter == 3) {
continue;
}
System.out.println(counter);
}
}
}