Skip to content
Qyubie Learn

Java tutorial · Beginner

Java Selection Structures: if, else if, Nested if, and switch

Make decisions in Java with if, if-else, else-if ladders, nested if, and switch, and learn to compare Strings correctly with equals().

  • Qyubie Learn Editorial Team
  • Published
  • 7 min read

Includes 2 quick checks you can do right here.

So far our programs ran every line, top to bottom. Real programs decide: pass or fail, valid or invalid input, which menu option was chosen. Java's selection structures run a block of code only when a condition is true.

By the end of this lesson you will be able to:

  • write if, if-else, and else if ladders,
  • nest one decision inside another,
  • use switch for menus and fixed choices, and
  • compare Strings correctly with .equals().

if

An if runs its block only when the condition is true:

int grade = 82;
if (grade >= 75) {
    System.out.println("Passed");
}
System.out.println("Done");

Output:

Passed
Done

The condition must be a boolean expression, and it goes in parentheses. The braces hold the code that depends on it.

if-else

else gives the other path, the one taken when the condition is false:

int grade = 70;
if (grade >= 75) {
    System.out.println("Passed");
} else {
    System.out.println("Failed");
}

Output:

Failed

Exactly one of the two blocks runs, never both and never neither.

The else-if ladder

For more than two outcomes, chain conditions with else if. Java checks them from the top and runs only the first one that is true.

int score = 88;
String remark;
if (score >= 90) {
    remark = "Excellent";
} else if (score >= 85) {
    remark = "Very Good";
} else if (score >= 80) {
    remark = "Good";
} else if (score >= 75) {
    remark = "Passed";
} else {
    remark = "Failed";
}
System.out.println(score + ": " + remark);

Output:

88: Very Good

88 is also >= 80 and >= 75, but those branches are never checked: the ladder stops at the first match. That's why the conditions go from the highest threshold down. In the opposite order, every passing score would say "Passed".

Quick check

What does this print?
int x = 15;
if (x > 5) {
    System.out.println("A");
} else if (x > 10) {
    System.out.println("B");
} else {
    System.out.println("C");
}

Nested if

An if can sit inside another one. Use this when the second question only makes sense after the first is answered:

boolean enrolled = true;
int units = 27;
if (enrolled) {
    if (units > 26) {
        System.out.println("Overload: needs the dean's approval");
    } else {
        System.out.println("Regular load");
    }
} else {
    System.out.println("Not enrolled");
}

Output:

Overload: needs the dean's approval

Deep nesting gets hard to read. Often && does the same job more simply: if (enrolled && units > 26).

Always use braces. Without them, an if controls only the next single statement, which causes bugs like this one:

int stock = 0;
if (stock > 0)
    System.out.println("In stock");
    System.out.println("Ships today");   // NOT part of the if!

Output:

Ships today

The indentation suggests both lines belong to the if, but Java ignores indentation. Only the first line is controlled by it.

Comparing Strings: equals, not ==

== on objects checks whether two variables refer to the same object, not whether the text matches. Text that comes from the keyboard, a file, or a calculation is a new object, so == often says false even when the words are identical.

String typed = new String("admin");   // like text read from the keyboard
System.out.println(typed == "admin");
System.out.println(typed.equals("admin"));
System.out.println("ADMIN".equalsIgnoreCase(typed));

Output:

false
true
true

Always use .equals() for Strings, and .equalsIgnoreCase() when upper- and lowercase shouldn't matter.

switch

switch picks a branch by matching one value against fixed cases. It's cleaner than a long ladder when you're checking one variable against exact values, as in a menu.

int choice = 2;
switch (choice) {
    case 1:
        System.out.println("Add student");
        break;
    case 2:
        System.out.println("View students");
        break;
    case 3:
        System.out.println("Exit");
        break;
    default:
        System.out.println("Invalid choice");
}

Output:

View students
  • switch works with int, char, String, and enums (and byte and short), but not double or boolean.
  • break ends the switch. Without it, execution falls through into the next case.
  • default runs when no case matches, like the final else.

Fall-through is sometimes useful, for example to group cases:

char grade = 'B';
switch (grade) {
    case 'A':
    case 'B':
        System.out.println("Great work");
        break;
    case 'C':
        System.out.println("Good");
        break;
    default:
        System.out.println("Keep trying");
}

Output:

Great work

Quick check

What does this print?
int day = 1;
switch (day) {
    case 1:
        System.out.print("Mon ");
    case 2:
        System.out.print("Tue ");
        break;
    case 3:
        System.out.print("Wed ");
}

The arrow switch (Java 14 and later)

Newer Java versions have a shorter form that uses ->. It never falls through, so there are no breaks to forget, and it can produce a value:

String day = "SAT";
String type = switch (day) {
    case "SAT", "SUN" -> "Weekend";
    case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday";
    default -> "Unknown";
};
System.out.println(type);

Output:

Weekend

Your instructor may ask for the classic form in exams. Know both.

Common mistakes

  • Putting a ; right after the condition: if (x > 0); ends the if there, and the block below always runs.
  • Ladder in the wrong order: check the highest threshold first.
  • Missing break in a classic switch, which causes accidental fall-through.
  • Comparing Strings with ==. Use .equals().
  • Leaving out braces, which makes only one statement conditional.

Summary

  • if runs a block when a condition is true; else handles the false case.
  • An else if ladder runs only the first true branch, so order your conditions carefully.
  • Nested ifs handle follow-up questions; && often makes them simpler.
  • switch matches one value against exact cases; use break to stop fall-through, and default for anything else.
  • Compare Strings with .equals().

Next lesson: iterative structures: repeating code with for, while, and do-while.

References and further reading