Java Decisions and Loops: if, switch, while, do-while, for and the Enhanced for
Up to now, our Java programs ran from top to bottom, one line after another. Real programs aren't like that. They need to make choices ("is the user logged in?") and repeat things ("check every item in the cart").
Java gives us two groups of tools for this:
-
Conditionals help the program decide:
if,else if,else, andswitch. -
Loops help the program repeat:
while,do-while,for, and the enhancedfor.
Let's go through each one, and I'll also share when to pick which, because that's the part tutorials often skip.
Part 1: Making decisions
if, else if, else
The if statement runs a block of code only when a condition is true.
int marks = 72;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 60) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
Java checks the conditions from top to bottom and runs the first one that is true. Then it skips the rest. Here, 72 is not >= 90, but it is >= 60, so we get "Grade B".
Two things to remember:
- The condition must be a
boolean(trueorfalse). Unlike some other languages, Java won't treat1or0as true or false. - Order matters. If you checked
marks >= 60first, a student with 95 would also get "Grade B", because 95 is also >= 60. Put the strictest condition first.
A mistake almost everyone makes: comparing strings with ==.
String city = "Pune";
if (city.equals("Pune")) { // correct
System.out.println("Welcome!");
}
For objects like String, == checks whether both sides are the same object in memory, not whether the text is the same. Use .equals() to compare the text.
The ternary operator (a shortcut)
For a simple either/or choice, you can write an if-else on one line:
int age = 20;
String result = (age >= 18) ? "Adult" : "Minor";
Read it as: "if age >= 18, use 'Adult', otherwise use 'Minor'." It's handy for small things. If you find yourself nesting them, go back to a normal if, because they get hard to read very fast.
switch
When you compare one value against many fixed options, a long else if ladder gets messy. That's where switch is cleaner.
The classic style looks like this:
int day = 3;
String name;
switch (day) {
case 1:
name = "Monday";
break;
case 2:
name = "Tuesday";
break;
case 3:
name = "Wednesday";
break;
default:
name = "Unknown";
}
See the break? It's important. Without it, Java doesn't stop at the matching case. It keeps running into the next case too. This is called fall-through:
int day = 1;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
break;
}
// Prints both "Monday" and "Tuesday"
Sometimes fall-through is useful (several cases sharing one result), but most of the time it's a bug waiting to happen.
The modern way (Java 14 and later) fixes this with arrows. No break, no fall-through, and the switch can even return a value:
int day = 6;
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid day";
};
This is shorter and safer. If your project uses a recent Java version, prefer this style.
if or switch? Use if when your conditions are ranges or complex (marks >= 60 && marks < 90). Use switch when you're matching one value against a list of exact options, like days, menu choices or status codes.
Part 2: Repeating things with loops
Every loop has the same three ingredients:
- A starting point
- A condition that decides whether to keep going
- An update that moves you toward the end
If you forget the third one, your loop never stops. That's an infinite loop, and it's the most common loop bug.
while
Use while when you don't know in advance how many times you'll repeat. The condition is checked before each round.
int count = 3;
while (count > 0) {
System.out.println("Countdown: " + count);
count--;
}
System.out.println("Liftoff!");
Output:
Countdown: 3
Countdown: 2
Countdown: 1
Liftoff!
Notice count--. That's our update. Remove it, and count stays 3 forever.
Since the check happens first, a while loop might run zero times. If count started at 0, nothing would print.
do-while
A do-while loop is almost the same, but the condition is checked after the body. That means it always runs at least once.
int number;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a number between 1 and 10: ");
number = sc.nextInt();
} while (number < 1 || number > 10);
This is a perfect fit for "ask the user first, then validate." You can't check their answer before you've asked the question. Notice the semicolon after the while (...). It's required here, and people forget it.
while or do-while? If the loop body must run at least one time (menus, input checks), use do-while. Otherwise, while is the usual choice.
for
When you know how many times to repeat, for is the neatest option because it puts all three ingredients on one line:
for (int i = 1; i <= 5; i++) {
System.out.println("Round " + i);
}
Read the header in three parts:
-
int i = 1is the start. It runs once. -
i <= 5is the condition. It's checked before every round. -
i++is the update. It runs after every round.
A very common mistake is the off-by-one error. Should it be i < 5 or i <= 5? Zero-based counting (like arrays) usually uses <. Counting from 1 usually uses <=. When in doubt, test with a small number and check by hand.
A for loop is really just a while loop with tidier packaging. Here's the same thing as a while:
int i = 1;
while (i <= 5) {
System.out.println("Round " + i);
i++;
}
Both work. The for version keeps the counter's setup and update in one place, so you're less likely to forget the update.
Enhanced for (for-each)
When you just want to go through every item in an array or a list, the enhanced for loop removes the extra noise:
String[] fruits = {"Apple", "Banana", "Mango"};
for (String fruit : fruits) {
System.out.println(fruit);
}
Read the : as "in". So: "for each fruit in fruits". There's no counter, no length check, and no chance of going past the end of the array.
It works on lists too:
List<Integer> scores = List.of(80, 92, 75);
int total = 0;
for (int score : scores) {
total += score;
}
But it has limits. Use a normal for instead when:
- You need the index (position) of each item.
- You want to go backwards or skip items (like every second one).
- You want to change the array's elements by position. The loop variable is just a copy of each value, so
fruit = "Kiwi"won't change the array. - You're removing items from a list while looping. That throws a
ConcurrentModificationException.
break and continue
Two small keywords give you extra control inside any loop:
-
breakstops the loop completely. -
continueskips the rest of the current round and moves to the next one.
for (int i = 1; i <= 10; i++) {
if (i == 3) continue; // skip 3
if (i == 6) break; // stop at 6
System.out.println(i);
}
// Prints: 1, 2, 4, 5
Use them when they make the code clearer, but don't overdo it. A loop full of break and continue is usually a sign that the logic can be written more simply.
So which one should I use?
Here's the quick way I think about it:
-
Choosing between two or three paths?
if / else if / else -
Matching one value against many exact options?
switch(the arrow style if you can) -
Repeat while something is true, and you don't know how many times?
while -
Must run at least once?
do-while -
You know how many rounds, or you need the index?
for -
Just visit every item in an array or list? enhanced
for
Common mistakes to watch for
- Forgetting the update (
i++) and creating an infinite loop. - Off-by-one errors with
<and<=. - Comparing strings with
==instead of.equals(). - Forgetting
breakin an old-styleswitchand getting fall-through. - Putting a semicolon right after
if (...)orfor (...), which makes the body run separately from the condition.
Wrapping up
Everything here comes down to two ideas: decide and repeat. Once you're comfortable with them, you can build almost any logic out of these small pieces, and the choice between them is mostly about picking the one that makes your intention clearest to the next person who reads your code (often you, a month later).
A good way to practice: write a small number-guessing game. It uses an if to compare guesses, a do-while to keep asking, and maybe a switch for a hint menu. Try it and see how the pieces fit together.
If this helped, or if you spotted something I should fix, let me know in the comments. I'm still learning too.
Top comments (0)