I have a question using Enum inside a switch statement in java:
I declare Enum in Java and use a variable of this type in the switch statement, which addresses all the possible cases for enum values. In this example, each case initializes a variable that was not initialized before the switch, but the compiler still gives me an error because javac does not recognize that all possible cases are covered:
public class EnumSwitchTest { public enum MyEnum { FOO, BAR } public static void main(String[] args) { test(MyEnum.FOO); test(MyEnum.BAR); } private static void test(MyEnum e) { String msg; switch (e) { case FOO: msg = "foo"; break; case BAR: msg = "bar"; break; }
Why can't the compiler detect that this switch will always initialize msg (or throw a NullPointerException because e is null )?
What I would like to achieve is a switch statement that handles all cases, but will lead to a compilation error if the Enum class is expanded in the future, but a new key is not added to the switch.
source share