Lesson 9 of 34

switch: Choosing Between Many Values

8 min 30 XP

switch picks one of many paths based on a value. Each case needs a break at the end, or the next case runs too (fall-through). default runs when nothing matches.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

switch also works with String and char values. Here is a tiny calculator.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Challenge

+30 XP

Read two numbers and an operator (+ - * /) and print the result. For any other operator print "Invalid". Input: 8 * 5 → Output: 40

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.