Switch-Case Statement in Java - Quiz

Total: 5 questions

1. 

Which types are allowed as the switch expression in a classic Java switch, and which are forbidden?

The allowed types are char, byte, short, int, their wrapper classes (Character, Byte, Short, Integer), enum (since Java 6), and String (since Java 7). Types such as long, float, double, and boolean are forbidden and cause a compilation error. The switch can only test for equality, so relational operators like >= or <= are not allowed either.

2. 

What is fall-through in a classic switch, and how do you prevent it?

Case constants are evaluated from top to bottom, and the first matching case becomes the entry point. Once execution enters that case, it continues into the corresponding block and all subsequent blocks until the end of the switch. This behavior is called fall-through. To stop it and exit the switch after a single block, use the break keyword at the end of each case. With the Java 14 arrow syntax (case 1 -> ...) fall-through does not happen at all, so break is not needed there.

3. 

What is the default section for, and does it have to be the last section in a switch?

The default section handles all values that are not explicitly listed in any case. It does not have to be placed last — it can appear anywhere in the switch. If no case constant matches, default becomes the entry point, and in a classic switch fall-through then continues into whatever sections follow it. In a classic switch default is optional, but in a switch expression it is required unless the expression is an enum whose constants are all covered.

4. 

What did switch expressions introduced in Java 14 change compared to the classic switch?

Switch expressions (standard since Java 14, preview in Java 12–13) let a switch return a value that can be assigned to a variable, e.g. String season = switch (month) { ... };. They add the arrow syntax (case 1 -> ...): after the arrow you write a single expression or a { } block, and there is no fall-through, so break is no longer needed. Multiple values can be grouped in one label separated by commas (case 12, 1, 2 -> ...). A switch expression must be exhaustive — cover every possible value.

5. 

What is the yield keyword used for, and how does it differ from break?

yield (added in Java 14) returns a value from a switch expression. It is used with the old colon syntax (case 12, 1, 2: yield "Winter";) and inside a { } block of the arrow syntax when you need to return a value after running some statements. break, by contrast, only terminates a switch statement and returns nothing. Another difference: yield is a reserved word, not a keyword, so outside the switch you can still declare a variable named yield, whereas you could never name a variable break or case.

Page 1 of 1