1. Switch statements
So far, we've been using `if`, `else if`, and `else` statements to control how our programs make decisions. In many cases, that's all we need. But when we're checking one value against several specific options, there's another tool that can make our code easier to read: the switch statement.
2. What is a switch?
A `switch` statement works like a set of multiple `if-else` checks. It's a great choice when we want to do something different based on a single variable's value. Let's say we get a bonus. If it's ten thousand, we buy a car. If it's five thousand, we take a trip. If it's one thousand, we save the money. Rather than writing three separate if checks, we can use a switch to handle all of that in one block.
3. Switch syntax
We start a switch with the keyword `switch`, followed by the variable or expression we want to check in parentheses. Then comes a code block with different case labels inside. Each case represents one of the possible values we want to handle. If the value of the expression matches a case, the code for that case runs.
4. Switch example
For example, if our switch is checking a `char` and the value is 'N', Java will compare 'N' to each case until it finds a match. When it does, it runs the matching case's code.
5. Break
To stop Java from continuing through the rest of the cases, we use the `break` statement. That's an important detail: `break` tells Java to stop checking once it finds a match. If we leave `break` out, Java keeps going - running the next case's code too.
6. Use of break
This can actually be useful. Let's say we want the same outcome for multiple values. If we don't include a break between those cases, they all fall through to the same block of code.
7. Default
There's also a `default` case, which runs only if none of the other cases match. It's like the final `else` in an `if-else` chain. The default case doesn't require a value to match, and it's usually placed at the end of the switch. It's optional and it's up to us if we want to include it.
8. Conditionals versus switch
Just like with if-else, we're building a conditional workflow - but switch statements are often easier to read when we're checking a single variable against several possibilities. That said, they don't work with every data type. In Java, a `switch` expression we want to check must be something like `int`, `byte`, `short`, `char`, or `String`.
9. Let's practice!
Now, you'll write your own switch statements and see how to combine cases to simplify your logic. Let's give it a try!