Java Loops
Java loops repeat a block of code while a condition is true. They save you from writing the same statement again and again, and they are how you process every item in an array or list.
The for Loop
A for loop has three parts: start (int i = 1), condition (i <= 5) and update (i++). Use it when you know how many times to repeat.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("3 x " + i + " = " + (3 * i));
}
}
}3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15
The Enhanced for-each Loop
To visit every element of an array or collection, the for-each loop is shorter and avoids index mistakes.
public class Main {
public static void main(String[] args) {
String[] fruits = {"Mango", "Apple", "Banana"};
for (String fruit : fruits) {
System.out.println("I like " + fruit);
}
}
}I like Mango I like Apple I like Banana
while and do-while Loops
A while loop checks its condition first and may run zero times. A do-while loop runs the body once before checking, so it always runs at least once.
public class Main {
public static void main(String[] args) {
int balance = 100;
int years = 0;
while (balance < 150) {
balance += balance / 10; // 10% growth
years++;
}
System.out.println(years + " years, balance " + balance);
int n = 10;
do {
System.out.println("Runs once, n = " + n);
} while (n < 5);
}
}5 years, balance 160 Runs once, n = 10
break and continue
break exits the loop immediately. continue skips the rest of the current iteration and moves to the next one.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
if (i > 7) break; // stop after 7
System.out.print(i + " ");
}
System.out.println();
}
}1 3 5 7
Nested Loops
A loop inside another loop runs completely for each step of the outer loop. This is useful for grids and tables.
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= row; col++) {
System.out.print("*");
}
System.out.println();
}
}
}* ** ***
Frequently asked questions
What is the difference between while and do-while in Java?
while checks the condition before each run, so the body may never execute. do-while checks after, so the body always runs at least once.
Can I modify a list inside a for-each loop in Java?
Adding or removing elements during a for-each over a collection throws ConcurrentModificationException. Use an Iterator with remove(), or removeIf().
How do I stop an infinite loop in Java?
Make sure the loop condition eventually becomes false, or use break when a stop condition is met. In a terminal, press Ctrl+C to kill a running program.