Today, we’re diving into another fundamental concept in Java programming: the switch
statement. If you’ve already learned about the if
statement (if not, check out this article about if
), you’ll find that switch
is another way to make decisions in your code. In some cases, it can make your programs more readable and efficient.
When to Use if
vs. switch
?
Here’s a simple guideline:
- Use
if
when:- You need to check a few different conditions, especially if they involve ranges or logical operators (e.g.,
age > 18 && age < 65
). - Conditions are varied, like checking numbers, strings, or complex expressions.
- You need to check a few different conditions, especially if they involve ranges or logical operators (e.g.,
- Use
switch
when:- You’re checking a single variable against several possible values.
- You want cleaner and more readable code compared to a long chain of
if-else
statements.
What Does switch
Look Like?
Here’s the basic structure of a switch
statement:
switch (variable) {
case value1:
// Actions to perform if variable == value1
break;
case value2:
// Actions to perform if variable == value2
break;
default:
// Actions to perform if none of the cases match
}
Key points:
variable
is the value being tested.- Each
case
checks if thevariable
matches a specific value. - The
break
statement prevents the code from “falling through” to the next case. - The
default
block runs if no cases match (likeelse
in anif
statement).
Example 1: Checking the Day of the Week
Let’s write a program that tells us what day it is based on a number (1 = Monday, 2 = Tuesday, etc.).
public class WeekDay {
public static void main(String[] args) {
int day = 3; // Day of the week
switch (day) {
case 1:
System.out.println("It's Monday.");
break;
case 2:
System.out.println("It's Tuesday.");
break;
case 3:
System.out.println("It's Wednesday.");
break;
case 4:
System.out.println("It's Thursday.");
break;
case 5:
System.out.println("It's Friday.");
break;
case 6:
System.out.println("It's Saturday.");
break;
case 7:
System.out.println("It's Sunday.");
break;
default:
System.out.println("Invalid day number!");
}
}
}
Explanation:
- If
day = 3
, the program prints: “It’s Wednesday.” - If
day = 8
, it falls to thedefault
block: “Invalid day number!”
Example 2: Grading System
Imagine a school where grades are represented by letters (A, B, C, D, F). Let’s use switch
to display feedback based on the grade.
public class GradeCheck {
public static void main(String[] args) {
char grade = 'B'; // Student's grade
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Good job!");
break;
case 'C':
System.out.println("Satisfactory.");
break;
case 'D':
System.out.println("Needs improvement.");
break;
case 'F':
System.out.println("Fail.");
break;
default:
System.out.println("Unknown grade.");
}
}
}
Why Use switch
?
Let’s compare a switch
with a similar if-else
chain:
if (grade == 'A') {
System.out.println("Excellent!");
} else if (grade == 'B') {
System.out.println("Good job!");
} else if (grade == 'C') {
System.out.println("Satisfactory.");
} else if (grade == 'D') {
System.out.println("Needs improvement.");
} else if (grade == 'F') {
System.out.println("Fail.");
} else {
System.out.println("Unknown grade.");
}
As you can see, the switch
version is cleaner and easier to read, especially when there are many conditions to check.
Example 3: Handling Multiple Cases Together
Sometimes, multiple cases should trigger the same action. For example, let’s check if today is a weekend:
public class Weekend {
public static void main(String[] args) {
int day = 6; // Day of the week
switch (day) {
case 6: // Saturday
case 7: // Sunday
System.out.println("It's the weekend! Time to relax.");
break;
default:
System.out.println("It's a weekday. Back to work!");
}
}
}
What to Keep in Mind About switch
switch
is great for simple equality checks – when you’re comparing one variable to multiple values.- It keeps your code clean – especially when compared to long chains of
if-else
statements. - Don’t forget the
break
statement – it stops the code from executing the next cases unintentionally. - The
default
block is optional – but it’s a good habit to include it for handling unexpected values.
Practice Challenges
Here are some fun challenges to practice your switch
skills:
- Check the month by number: Write a program that prints the name of a month (1 = January, 2 = February, etc.).
- Animal guessing game: Write a program that assigns animals to numbers (1 = Dog, 2 = Cat, 3 = Lion) and prints the result.
- Extended grading system: Modify the grade example to include A+ and A- for more detailed feedback.
The switch
statement is a powerful tool for simplifying your code when you need to compare one value against multiple options. It’s a great complement to the if
statement, and now you know when to use each. Happy coding!