How do if-else and switch differ in Java, and when should you reach for each one?
Both of them choose between options, but they work in different ways.
An if statement works on a condition that is either true or false. You can compare values, you can use the logical operators, and you can build conditions that have nothing to do with matching one value against a list.
A switch works by taking one value and comparing it against a list of fixed labels. It is a better fit when you have one value and several known cases for it, such as a status code or a day of the week.
public class Main {
public static void main(String[] args) {
int score = 72;
// An if statement is right for conditions and for ranges.
if (score >= 90) {
System.out.println("grade: A");
} else if (score >= 60) {
System.out.println("grade: pass");
} else {
System.out.println("grade: fail");
}
// A switch is right for one value against a list of labels.
String grade;
switch (score) {
case 100:
grade = "perfect";
break;
case 90:
grade = "excellent";
break;
default:
grade = "other";
}
System.out.println("label: " + grade);
}
}
So when do you reach for each one? Use if when the condition is a range, when it is a comparison between two values that are not the same thing, or when you have more than two or three branches. Use switch when one value decides between several fixed labels, and when those labels are all constants of the same type.
One more difference is worth knowing. A switch on a String compares the whole text, and it is case sensitive, so "MONDAY" and "monday" are two different things. An if can use equalsIgnoreCase when you want to be forgiving about capital letters.
The next question in this topic looks at the modern form of switch that does not need break.