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.