Java Enums in Switch Statements – Ensuring Completeness

enumjavaswitch statement

I feel like I should be able to find an answer to this, but it turns out to be harder to search than expected… so:

In C#, when we do something like:

enum MyEnumClass { A, B };

static String Test(MyEnumClass m)
{
    switch (m)
    {
        case MyEnumClass.A: return "the value was A";
        case MyEnumClass.B: return "the value was B";
        //default: return "The value was ????"; //we need to uncomment this
    }
}

we get a "not all code paths return a value" error and need to add the default case, because enums are actually just numbers in disguise and we might be calling the method with a value we didn't cover like so:

test((MyEnumClass)53)

However, I don't think we can do such a thing (call the method with anything else than our two enum-values) in Java (Or can we?). Still, if we write similar code in Java, we get a similar error. If this is the case, is there any reason why the compiler cant figure out such a switch statement is complete and hence that the default case isn't necessary?

Best Answer

Imagine what would happen if you decided that enum needed a new value, but that enum is being used in a thousand switch statements just like that one. Because Java forced them all to have a default case when they wrote those switches, then whatever logging statement or exception throw everyone chose to put there will probably save them a lot of headaches when you make that change.

If the Java compiler accepted those thousand switch statements with only two cases because they cover all the values...then you can't ever add your third value, because nobody's code would compile anymore. And as ddyer pointed out, separate compilation makes such a check impossible in the general case.

So you're left with either always requiring a default case, or never requiring it. Since Java has a very different philosophy from C++, it chose the former.

Also, Enums in Java can be null, so you have to be prepared for that.