Java tutorialLesson 6 of 18 · tap to see all lessons
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, andelse ifladders, - nest one decision inside another,
- use
switchfor 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
DoneThe 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:
FailedExactly 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 Good88 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
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 approvalDeep 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 todayThe 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
trueAlways 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 studentsswitchworks withint,char,String, and enums (andbyteandshort), but notdoubleorboolean.breakends the switch. Without it, execution falls through into the next case.defaultruns when no case matches, like the finalelse.
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 workQuick check
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:
WeekendYour instructor may ask for the classic form in exams. Know both.
Common mistakes
- Putting a
;right after the condition:if (x > 0);ends theifthere, and the block below always runs. - Ladder in the wrong order: check the highest threshold first.
- Missing
breakin a classic switch, which causes accidental fall-through. - Comparing Strings with
==. Use.equals(). - Leaving out braces, which makes only one statement conditional.
Summary
ifruns a block when a condition is true;elsehandles the false case.- An
else ifladder runs only the first true branch, so order your conditions carefully. - Nested
ifs handle follow-up questions;&&often makes them simpler. switchmatches one value against exact cases; usebreakto stop fall-through, anddefaultfor anything else.- Compare Strings with
.equals().
Next lesson: iterative structures: repeating code with for, while, and do-while.