Why do I get a “variable might not have been initialized” compiler error in my switch block?

前端 未结 1 1402
眼角桃花
眼角桃花 2020-11-30 15:24

I\'m encountering \"a variable might not have been initialized\" error when using switch block.

Here is my code:

public static void foo(int month)
{
         


        
相关标签:
1条回答
  • 2020-11-30 15:49

    If month isn't 1 or 2 then there is no statement in the execution path that initializes monthString before it's referenced. The compiler won't assume that the month variable retains its 2 value, even if month is final.

    The JLS, Chapter 16, talks about "definite assignment" and the conditions under which a variable may be "definitely assigned" before it's referenced.

    Except for the special treatment of the conditional boolean operators &&, ||, and ? : and of boolean-valued constant expressions, the values of expressions are not taken into account in the flow analysis.

    The variable monthString is not definitely assigned prior to being referenced.

    Initialize it before the switch block.

    String monthString = "unrecognized month";
    

    Or initialize it in a default case in the switch statement.

    default:
        monthString = "unrecognized month";
    

    Or throw an exception

    default:
        throw new RuntimeExpception("unrecognized month " + month);
    
    0 讨论(0)
提交回复
热议问题