5.2 Switch Challenge
This lesson is the small switch challenge announced at the end of the previous video. The exercise: write a switch that tests a char variable instead of an int. The cases should cover the letters 'A', 'B', 'C', 'D' and 'E', each printing "X was found". Anything else lands in the default branch with a "not found" message. Take a few minutes to try it on your own before reading the solution.
Solution walk-through
We declare char charValue = 'A';. As a reminder, char is a Unicode character delimited by single quotes. The switch takes charValue as its expression and we add five case branches, one per letter. Inside each branch we use System.out.println(charValue + " was found"); followed by break;. The trailing default prints "not found" and also ends with a break.
case 'A':...break;case 'B':...break;case 'C':/case 'D':/case 'E':with the same shape.default:prints "not found" and breaks.
Running the program with 'A' prints "A was found". Switching to 'B' or 'E' hits the matching case. Trying 'F' falls into the default. Be careful with case sensitivity: a lowercase 'a' will not match the uppercase 'A' branch because the characters are different. A small challenge, but a useful reminder that switch in Java also works on char values, not just integers.
Summary
This lesson demonstrates a practical challenge on Java switch statements using char data type instead of the typical int. The tutorial walks through creating a switch statement that evaluates character values (a, b, c, d, e), displays appropriate messages for matched cases, and handles unmatched values with a default clause. Key concepts include the importance of break statements, case sensitivity, and proper fall-through prevention.
Key points
- Switch statements work with char type variables for character evaluation
- Each case must include a break statement to prevent unintended fall-through to subsequent cases
- The default clause executes when none of the defined cases match the input value
- Switch matching is case-sensitive: uppercase 'A' and lowercase 'a' are treated as different values
- String concatenation can be used in case outputs to display dynamic messages
FAQ
What data type is used in this switch challenge?
The challenge uses a char (character) data type instead of the more commonly used int type, demonstrating switch statement versatility.
What happens if a case statement is missing a break?
Without a break statement, execution will fall through to the next case, potentially executing unintended code blocks.
Why doesn't lowercase 'a' match the case 'A'?
Switch statements are case-sensitive, so uppercase and lowercase characters are treated as distinct values and require separate case definitions.