Java Loops
A loop runs the same block of code again and again while a condition is true.
The while Loop
A while loop checks the condition first, then runs the block:
Example
public class Main {
public static void main(String[] args) {
int count = 1;
while (count <= 3) {
System.out.println("Count: " + count);
count++;
}
}
}Count: 1 Count: 2 Count: 3
Always change the loop variable inside the loop. If count never grows, the condition stays true forever and you get an infinite loop.
The do...while Loop
A do...while loop runs the block once first, then checks the condition. It always runs at least one time:
Example
int n = 10;
do {
System.out.println("n is " + n);
n++;
} while (n < 5);n is 10
The for Loop
Use for when you know how many times to repeat. It puts the start, the condition and the step on one line:
Example
for (start; condition; step) {
// code
}Example
public class Main {
public static void main(String[] args) {
// 7 times table
for (int i = 1; i <= 5; i++) {
System.out.println("7 x " + i + " = " + (7 * i));
}
}
}7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
The for-each Loop
The for-each loop goes through every item in an array, one by one:
Example
public class Main {
public static void main(String[] args) {
String[] fruits = {"Mango", "Banana", "Guava"};
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}Mango Banana Guava
break and continue
| Keyword | What it does |
|---|---|
break | Leaves the loop completely |
continue | Skips the rest of this round and goes to the next one |
Example
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 4) {
continue; // skip 4
}
if (i == 7) {
break; // stop at 7
}
System.out.print(i + " ");
}
}
}1 2 3 5 6
Adding Numbers with a Loop
Loops are often used to build a total:
Example
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum: " + sum);Sum: 5050
Exercise
Exercise
Which loop always runs its block at least once?
