Skip to content
Codewilds

Lesson 5 of 34 · Fundamentals

Java if/else and switch Statements

easy10 XP3 min readFree lesson

Programs become interesting when they can make decisions: open the gate if the player has the key, show a warning if the password is too short. In Java you make decisions with if/else and switch, driven by boolean expressions that are either true or false.

Comparisons and logical operators

int level = 12;
level == 12   // true  (equal — two equals signs!)
level != 12   // false (not equal)
level > 10    // true
level <= 9    // false

Combine conditions with the logical operators && (and), || (or) and ! (not):

boolean hasKey = true;
boolean isNight = false;
hasKey && !isNight          // true: has the key AND it is not night
level < 5 || hasKey         // true: at least one side is true

&& and || short-circuit: if the left side already decides the answer, the right side is never evaluated. That is why name != null && name.length() > 3 is safe even when name is null.

if, else if, else

int hp = 35;
if (hp > 70) {
    System.out.println("Healthy");
} else if (hp > 30) {
    System.out.println("Wounded");
} else {
    System.out.println("Critical!");
}
Wounded

Java checks the conditions from top to bottom and runs only the first matching branch. Order matters: if you tested hp > 30 first, a hero with 90 HP would be reported as "Wounded".

Inside a method you can also return from a branch, which ends the method immediately — a neat way to avoid deeply nested else blocks.

The ternary operator

For a quick either/or value, use condition ? valueIfTrue : valueIfFalse:

String status = hp > 0 ? "alive" : "defeated";

switch

When you compare one value against many fixed options, switch is clearer than a long if chain. Modern Java (14+) has switch expressions with arrows: no fall-through, several labels per case, and the whole switch produces a value:

String day = "Tuesday";
int hours = switch (day) {
    case "Saturday", "Sunday" -> 0;
    case "Friday" -> 6;
    default -> 8;
};

The older switch statement with colons is still common in existing code. There, each case needs a break, otherwise execution falls through into the next case:

switch (day) {
    case "Saturday":
    case "Sunday":
        System.out.println("Rest");
        break;
    default:
        System.out.println("Work");
}

You can switch on int, char, String and enum values.

Common mistakes

  • if (level = 12) — a single = is assignment; comparison is ==. Java refuses to compile it, because the condition must be a boolean.
  • Comparing Strings with == instead of equals (see the previous lesson). switch on a String uses equals for you.
  • Forgetting break in an old-style switch statement, so the next case runs too.
  • Checking a wide condition before a narrow one: if (score >= 60) before if (score >= 90) means nobody ever gets an A.

Assignment

Implement three methods in Main:

  1. grade(int score) — returns "A" for 90–100, "B" for 80–89, "C" for 70–79, "D" for 60–69 and "F" for 0–59. Any score below 0 or above 100 returns "invalid".
  2. dayType(String day) — use a switch: "Saturday" and "Sunday" return "weekend", "Monday" to "Friday" return "weekday", anything else returns "unknown". Names are case-sensitive.
  3. canEnter(int age, boolean hasTicket) — the arena lets you in if you have a ticket and are at least 12, or if you are 65 or older (seniors enter free, ticket or not).

If/else and conditions in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+10 XP

Press Run to execute your code, or Submit to check it against the tests.