Java Loops: for, while, do-while and for-each
A loop checks a condition, runs the body, updates, and goes round again. Five small programs: a for loop, a running sum to 15, a while loop that doubles Priya's savings, a do-while menu and a for-each over prices.
What you will learn
- Name the three parts of a for loop: start, check and update
- Keep a running total in a loop and avoid the off-by-one mistake
- Choose between for, while, do-while and for-each for a job
- Spot and fix an infinite loop
Before you start
- Java if, else and switch
Say you want to greet Emma, Jack, Priya and Lucas. You could copy and paste the same line four times, but that falls apart quickly. A loop repeats an action for you, like a conveyor belt that keeps going round.
Check, run the body, update
A loop has three parts:
- a start value:
int i = 1 - a check (the stopping rule):
i <= 5 - an update:
i++
Each pass, the loop checks the condition, runs the body, then updates. It stops the first time the check is false.
A for loop
package org.studyeasy.s02l10;
public class Ex01_ForLoop {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Hello, user " + i);
}
}
}
Hello, user 0
Hello, user 1
Hello, user 2
Hello, user 3
Hello, user 4
All three parts sit in the header. The body runs once per pass with i at 0, 1, 2, 3, 4. When i reaches 5 the check fails, which is why "user 5" never prints. Change the check to i <= 5 and the loop runs six times.
A loop that keeps a total
package org.studyeasy.s02l10;
public class Ex02_RunningSum {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
System.out.println("i = " + i + ", sum = " + sum);
}
System.out.println("Total: " + sum);
}
}
i = 1, sum = 1
i = 2, sum = 3
i = 3, sum = 6
i = 4, sum = 10
i = 5, sum = 15
Total: 15
sum lives outside the loop so every pass can add to it. <= includes the 5. The last println sits after the closing brace, so it prints once, when the loop is done.
Write i < 5 instead and the 5 is never added: the total drops to 10. That's the classic off-by-one mistake.
A while loop: until a goal is hit
package org.studyeasy.s02l10;
public class Ex03_WhileLoop {
public static void main(String[] args) {
double balance = 1000;
int year = 0;
while (balance < 2000) {
balance = balance * 1.10;
year++;
}
System.out.println("Priya reaches " + Math.round(balance) + " after " + year + " years");
}
}
Priya reaches 2144 after 8 years
A while only has the check. The start values are set before the loop, and the update lives inside the body. Use it when you don't know the count up front: here, keep growing the balance by 10% a year until it passes 2000.
A do-while loop: at least once
package org.studyeasy.s02l10;
public class Ex04_DoWhile {
public static void main(String[] args) {
int count = 10;
do {
System.out.println("Menu shown, count = " + count);
count++;
} while (count < 5);
System.out.println("Count is now " + count);
}
}
Menu shown, count = 10
Count is now 11
The check comes last. 10 < 5 is false, yet the body already ran once. Turn it into a plain while (count < 5) and the menu line never appears. Use do-while when something must happen at least once, like showing a menu.
A for-each loop: one pass per item
package org.studyeasy.s02l10;
public class Ex05_ForEach {
public static void main(String[] args) {
int[] prices = {10, 20, 30};
int total = 0;
for (int p : prices) {
total += p;
System.out.println("p = " + p + ", total = " + total);
}
System.out.println("Total: " + total);
}
}
p = 10, total = 10
p = 20, total = 30
p = 30, total = 60
Total: 60
prices is an array, a series of values in one variable (more in Java arrays). Read the header as "for each p in prices". p holds one price per pass, and there's no counter or stop condition to get wrong. Add a 40 to the array and the loop picks it up by itself: total 100.
Forget the update and the loop hangs
Take a while loop that prints users but has no i++ in its body:
// buggy on purpose: nothing changes i
int i = 0;
while (i < 5) {
System.out.println("Hello, user " + i);
}
i stays 0, 0 < 5 is true every time, and the same line prints forever. That's an infinite loop; in IntelliJ, press the red stop square. The fix is the missing update. Something in the body must move the condition toward false.
Pick the loop that fits
| Loop | Use it when |
|---|---|
for | you count passes with a counter |
while | you loop until something changes |
do-while | the body must run at least once |
| for-each | you walk through every item in a series |
for and while can do each other's jobs, so pick whichever reads better. Next, control a loop from the inside with break, continue and nested loops.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
Install JDK 25 (Microsoft Build of OpenJDK) with JAVA_HOME, install IntelliJ IDEA, then point a run configuration at the JDK and the main class and run Hello World.
Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
Open IntelliJ's AI Chat, pick Claude Agent (the agent behind Claude Code) or Copilot and a model, ask in plain words for Main.java to print the date and time, review the change, and run it.
Java Hello World with Maven: What the JDK Does and What Maven Adds
javac compiles HelloWorld.java into bytecode and java runs it on the JVM. Maven adds one pom.xml, the same folders in every project and one build command. Then a real Maven Hello World in IntelliJ.
Java Variables, Keywords and Naming Rules
A variable is a labelled jar that holds one value at a time. Four small programs show declaring, reassigning, the names Java accepts, the keywords it reserves, and why daysUntilLaunch beats d.
