Test 5 - Free Java SE 25 certification Mock test - Exam Code 1Z0-831-Oracle certified Java SE 25 Professional
Switch has probably seen as much evolution as any other Java feature and this free Java SE 25 mock test for the 1Z0-831 exam is designed to make sure you can spot the difference between the classic switch statement (with its colon labels and fall through) and the modern switch expression (with its arrows and yield). You're expected to be able to tell them apart in the exam.
You start with the rules that govern whether or not code will compile. A switch expression must produce a value for every possible input so the questions all look at exhaustiveness with regards to enums, sealed hierarchies and a default case. You'll see what happens when a case is missing, when two labels overlap and when a more specific pattern appears after a more general one (which the compiler will not allow).
Fall through is the next one. In a colon style statement you simply omit the break and the execution continues into the subsequent cases. The puzzle combines this with a default in the middle of the block. You'll be looking at these very carefully and then you'll be comparing them to the arrow style cases which never fall through. You can't mix arrow and colon labels in the same switch and you'll be looking out for that error very quickly.
Pattern matching is dealt with in full. Type patterns, record patterns and guarded cases (using the 'when' keyword) are all covered, as are nulls via 'case null'. You'll be able to predict which branch will be taken for a given object and know when a pattern variable is in scope. Selector types (strings, enums, wrapper types etc) are also looked at as are the types which are not allowed.
The yield statement in itself is a subject for its own set of questions. You'll see block bodies in arrow cases, nested switch expressions and the difference between yield and return. Each of the explanations shows the decision path so you're learning the principle rather than the answer. There will be a few instances where the code appears to be correct but in fact fails, because one of the branches yields nothing. You have to read each case very carefully.
Finally a few items compare switch with if-else chains and the ternary operator, so you can pick the cleanest option. Do the test under timed conditions, go through the explanations for anything you've got wrong and then re-do it until exhaustion and scope rules are second nature. This topic is well worth mastering as switch patterns come up in the records and sealed types questions as well.
