Skip to main content
PProfileMatch

Java If-Else, Switch and Loops

ProgrammingLesson 3 of 65 min read

What you'll learn

  • Make decisions with if, else if, else and the ternary operator
  • Use modern switch expressions and avoid old-style fall-through bugs
  • Choose between for, while, do-while and the enhanced for loop
  • Control loop flow with break and continue

On this page

  1. if, else if and else
  2. switch: statement and expression
  3. for, while and do-while
  4. The enhanced for loop, break and continue
  5. Common mistakes
  6. How this shows up in interviews and real projects

A program that only runs top to bottom can print things, but it cannot decide or repeat. Conditions let your code choose a path and loops let it repeat work, and together they power everything from grade calculators to checkout totals. This lesson shows each construct with an example you can run.

if, else if and else

An if statement runs a block only when its condition is true. The condition must be a boolean expression, built from comparison operators (==, !=, <, >, <=, >=) and logical operators (&& for and, || for or, ! for not). Java checks an else if chain from top to bottom and runs only the first branch that matches, so put the most specific condition first.

Grades.java
public class Grades {
    public static void main(String[] args) {
        int marks = 72;
        if (marks >= 90) {
            System.out.println("Grade A");
        } else if (marks >= 75) {
            System.out.println("Grade B");
        } else if (marks >= 60) {
            System.out.println("Grade C");
        } else {
            System.out.println("Needs improvement");
        }

        boolean hasId = true;
        int age = 17;
        if (age >= 18 && hasId) {
            System.out.println("Entry allowed");
        } else {
            System.out.println("Entry denied");
        }

        String status = marks >= 40 ? "Pass" : "Fail";
        System.out.println(status);
    }
}

Output

Grade C
Entry denied
Pass

The last two lines use the ternary operator, condition ? valueIfTrue : valueIfFalse, a compact way to pick between two values. Keep it for simple choices; nested ternaries are hard to read.

switch: statement and expression

When you compare one value against many fixed options, switch is cleaner than a long chain of else if. Since Java 14 you can use a switch expression with arrow labels. It returns a value, allows several labels per case, and has no fall-through. The older colon-style switch still exists and still needs a break after each case, otherwise execution continues into the next case.

Days.java
public class Days {
    public static void main(String[] args) {
        int day = 6;
        String type = switch (day) {
            case 1, 2, 3, 4, 5 -> "Weekday";
            case 6, 7 -> "Weekend";
            default -> "Invalid day";
        };
        System.out.println(day + " is a " + type);

        String command = "refund";
        switch (command) {
            case "buy":
                System.out.println("Adding to cart");
                break;
            case "refund":
                System.out.println("Starting refund");
            case "cancel":
                System.out.println("Cancelling order (fall-through!)");
                break;
            default:
                System.out.println("Unknown command");
        }
    }
}

Output

6 is a Weekend
Starting refund
Cancelling order (fall-through!)

The second switch is deliberately buggy. The refund case has no break, so it also runs the cancel case. This is why new code should prefer the arrow form, which cannot fall through.

for, while and do-while

Use a for loop when you know how many times to repeat, since it packs the start, the condition and the step into one line. Use a while loop when you repeat until something becomes true, and you do not know in advance how many rounds that takes. A do-while loop checks its condition after the body, so the body always runs at least once, which suits "ask, then validate" patterns.

Loops.java
public class Loops {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Round " + i);
        }

        int balance = 1000;
        int years = 0;
        while (balance < 1500) {
            balance += balance / 10;
            years++;
        }
        System.out.println("Years: " + years + ", balance: " + balance);

        int attempts = 0;
        do {
            attempts++;
        } while (attempts < 3);
        System.out.println("Attempts: " + attempts);

        int[] marks = {45, 82, 67, 91, 30};
        int sum = 0;
        for (int m : marks) {
            sum += m;
        }
        System.out.println("Average: " + (double) sum / marks.length);

        for (int m : marks) {
            if (m < 40) {
                continue;
            }
            if (m > 90) {
                System.out.println("Topper found: " + m);
                break;
            }
            System.out.println("Passed with " + m);
        }
    }
}

Output

Round 1
Round 2
Round 3
Years: 5, balance: 1610
Attempts: 3
Average: 63.0
Passed with 45
Passed with 82
Passed with 67
Topper found: 91

Walk through the savings loop to see why it works: 1000 grows by 10 percent each pass (1100, 1210, 1331, 1464, 1610), and after the fifth pass the balance is no longer below 1500, so the loop ends with years at 5.

The enhanced for loop, break and continue

The enhanced for loop (for (int m : marks)) reads as "for each mark in marks". Use it whenever you only need the values and not the index, because it removes the chance of an off-by-one error. Switch back to a classic indexed for if you need the position, or need to change elements by index.

Inside any loop, break exits the loop immediately and continue skips the rest of the current round and jumps to the next one. In the last loop above, 30 is skipped by continue, and the loop stops at 91 through break, so the later values are never visited.

Common mistakes

  • Using `=` instead of `==`. if (marks = 90) fails with error: incompatible types: int cannot be converted to boolean.
  • Forgetting to update the loop variable. A while (balance < 1500) loop that never changes balance runs forever, and your terminal appears to hang. Press Ctrl+C to stop it.
  • Off-by-one in a for loop. for (int i = 0; i <= marks.length; i++) goes one step too far and throws ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5. Use < with length.
  • A stray semicolon. if (x > 5); or for (...); ends the statement immediately, so the block below runs unconditionally or only once. It compiles without a warning, which makes it hard to spot.
  • Missing `break` in an old-style switch. Execution falls through into the next case, as the buggy switch above showed.
  • Comparing strings with `==` in conditions. Use .equals() so the condition checks the text.

How this shows up in interviews and real projects

Almost every beginner coding question, such as FizzBuzz, finding the largest value, counting vowels or checking for a prime number, is a loop with an if inside it. Interviewers watch for correct boundaries, early exits with break, and clear variable names. In real projects you will often replace manual loops with collection methods, but the logic you write here is what those methods do internally. For a roadmap of what to practise next, see coding interview prep for self-taught developers.

Try it yourself

Write a program that stores an array of 10 order amounts. Loop over them to print how many orders are above 1000, skip any negative (refunded) amounts with continue, and stop with break as soon as the running total passes 10000. Print the final count and total.

Show a hint

Keep two variables, count and total, outside the loop. Check for negative values first, update the total, check the break condition, then increment the count.

Key takeaways

  • if conditions must be boolean; use &&, || and ! to combine tests, and always use braces.
  • Prefer arrow-style switch expressions, which return a value and cannot fall through.
  • Use for for a known count, while for repeat-until, do-while when the body must run once, and enhanced for to visit every element.
  • break leaves the loop, continue skips to the next round, and a stray semicolon after if or for is a silent bug.

Test yourself

A trick from this lesson's ride: do-while: do first, ask later. The check sits at the exit door. Four more tricks like it wait along the route, each followed by a question.

Ride this lesson

Frequently asked questions

What is the difference between break and continue in Java?

break exits the entire loop (or switch) immediately. continue skips only the rest of the current iteration and moves on to the next one. Use break to stop searching once you have found a result and continue to ignore values you do not want.

When should I use a switch instead of if-else in Java?

Use switch when you compare a single value against several fixed constants, such as menu choices, day numbers or command strings. Use if-else when conditions involve ranges or combine several variables. Switch expressions with -> are the safer form because they cannot fall through.

What is the difference between a for loop and a while loop in Java?

A for loop is best when you know the number of iterations, since the initialisation, condition and update sit on one line. A while loop is better when you repeat until a condition changes and the count is unknown. Both can express the same logic.