为什么我的 switch 块中出现 "variable might not have been initialized" 编译器错误?

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

我在使用开关块时遇到 "a variable might not have been initialized" 错误。

这是我的代码:

public static void foo(int month)
{
    String monthString;
    switch (month)
    {
        case 1: monthString = "January";
                break;
        case 2: monthString = "February";
                break;
    }
    System.out.println(monthString);
}

错误:

Switch.java:17: error: variable monthString might not have been initialized
        System.out.println (monthString);

据我所知,当您尝试访问未初始化的变量时会发生此错误,但是当我在 switch 块中为其赋值时我是否没有初始化它?

同样,即使月份是编译时常量,我仍然收到相同的错误:

public static void foo()
{
    int month = 2;
    String monthString;
    switch (month)
    {
        case 1: monthString = "January";
                break;
        case 2: monthString = "February";
                break;
    }
    System.out.println(monthString);
}

如果 month 不是 12,则执行路径中没有语句在引用之前初始化 monthString。编译器不会假定 month 变量保留其 2 值,即使 monthfinal.

JLS, Chapter 16,讨论了 "definite assignment" 以及变量在被引用之前可能 "definitely assigned" 的条件。

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.

变量monthString在被引用之前没有明确赋值。

switch 块之前初始化它。

String monthString = "unrecognized month";

或者在switch语句中的default情况下初始化。

default:
    monthString = "unrecognized month";

或者抛出异常

default:
    throw new RuntimeExpception("unrecognized month " + month);