← Learning Hub
Beginner

Conditions and Loops

if / else

Control flow means deciding which lines run and how many times. By default Java runs statements top to bottom; if, switch and loops change that order. Almost every program combines these: "for each order, if it's paid, ship it, otherwise send a reminder".

An if condition must be a boolean - true or false. Combine conditions with && (and), || (or) and ! (not).

Example
You can edit this code.

switch

switch is a cleaner way to compare one value against many fixed options (days, menu choices, order statuses). Each case is one option, and default handles anything else. It works with numbers, characters, Strings and enums.

Example
String day = "SUN";
switch (day) {
    case "SAT":
    case "SUN":
        System.out.println("Weekend sale");
        break;
    default:
        System.out.println("Normal prices");
}

Loops

Java has three main loops. for is best when you're counting ("repeat 10 times"). The enhanced for loop for (String item : cart) goes through every item in an array or list. while repeats as long as a condition is true, for when you don't know the number of rounds in advance. break leaves a loop early; continue skips to the next round.

Example
for (int i = 1; i <= 3; i++) {
    System.out.println("Item " + i);
}

int stock = 3;
while (stock > 0) {
    stock--;
}

String[] items = {"Pen", "Book", "Bag"};
for (String it : items) {           // enhanced for loop
    System.out.println(it);
}
Do not forget break in a switch. Without it, the code carries on into the next case.
Key points
  • if / else choose between paths using a boolean condition.
  • switch compares one value with many cases - remember break.
  • for, enhanced for and while repeat code.

📝 Test yourself

1. Which loop is best for going through every item in an array?
2. What happens if you leave out break in a switch case?
3. Fill in the keyword for the other branch of an if:
if (x > 0) { ... } { ... }