Back to questions
JuniorTheoryCommon
What happens when the program is compiled and run?
public class Main {
public static void main(String[] args) {
int n = 3;
String s = switch (n) {
case 1 -> "one";
case 2 -> "two";
};
System.out.println(s);
}
}It does not compile
- Expecting
nullor a blank line: a switch expression must cover every possible value ofn, and withoutdefaultthe compiler rejects it. - Expecting a run-time error: the compiler checks coverage before the program runs, whatever value
nholds.
- How does
yieldhand a value out of a block branch of a switch expression? - Why does a switch expression over an
enumneed nodefaultwhen it lists every constant?