5.1 Switch
This lesson introduces the Java switch statement. We open IntelliJ, declare int value = 1; and reproduce a familiar pattern: if (value == 1) prints "The value is 1"; else if (value == 2) prints "The value is 2"; otherwise we print "The value is not 1 or 2". Changing the variable shows the right branch being taken.
This works well for two or three branches, but if you have ten values to test, the chain of if/else if quickly becomes hard to read. The cleaner alternative is the switch statement, which expresses the same logic in a more compact way.
Rewriting the same logic with switch
int value = 1;
switch (value) {
case 1:
System.out.println("The value is 1");
break;
case 2:
System.out.println("The value is 2");
break;
default:
System.out.println("The value is not 1 or 2");
}
- Each
casematches one literal value of the switched variable. - The
breakstatement exits theswitchso execution does not fall through to the next case. - The
defaultclause is the equivalent ofelseand catches every value not handled by acase.
Running the program with value = 1 prints the first message; setting value = 2 prints the second one. In the next video we will tackle a small switch challenge to practise the syntax.
Summary
This lesson introduces the switch statement as an efficient alternative to multiple if-else conditions in Java. The video demonstrates how to declare a switch block with cases, use the break statement to exit each case, and implement a default case equivalent to an else clause. Through practical examples with integer values, learners will understand how switch statements provide cleaner and more organized code when testing multiple conditions.
Key points
- Switch statements provide a cleaner alternative to multiple if-else conditions, especially when testing a single variable against many values
- Each case must end with a break statement to exit the switch block; without it, the program continues executing subsequent cases
- The default case acts as a fallback, similar to an else clause, when none of the case values match
- Switch syntax: switch(variable) { case value: statements; break; ... default: statements; }
- Use switch when you have 10 or more conditions to test, as it keeps code better organized than nested if-else
FAQ
What is the purpose of the break statement in a switch case?
The break statement terminates the switch block and prevents the program from executing subsequent cases. Without break, the code continues to the next case even if the condition was already matched.
What does the default case do in a switch statement?
The default case is executed when none of the other case values match the switch expression. It functions exactly like an else clause in an if-else structure.
When should I use switch instead of if-else?
Use switch when you need to test a single variable against many specific values. It provides cleaner, more organized code compared to multiple if-else statements, especially with 10 or more conditions.