为什么编译器会抱怨某个变量可能没有在一个永远不会访问它的分支中初始化?

时间:2017-02-10 15:35:57

标签: java compiler-errors

考虑只有这些方法的类的主体:

Integer getA()
{
    return 0;
}

Integer getB()
{
    return 1;
}

void testJava1()
{
    final Integer a1, b1;
    if ((a1 = getA()) != null && (b1 = getB()) != null)
    {
        System.out.println(a1 + " and " + b1); // fine
    }
}

void testJava2()
{
    final Integer a1, b1;
    final boolean condition = ((a1 = getA()) != null) && ((b1 = getB()) != null);
    if (condition)
    {
        System.out.println(a1 + " and " + b1); // variable might have been not initialized???
    }
}

void testJava3()
{
    final Integer a1, b1;
    final boolean conditionA = (a1 = getA()) != null;
    final boolean conditionB = (b1 = getB()) != null;
    if (conditionA && conditionB)
    {
        System.out.println(a1 + " and " + b1); // fine
    }
}

void testJava4()
{
    final Integer a1, b1;
    final boolean conditionA = (a1 = getA()) != null;
    final boolean conditionB = (b1 = getB()) != null;
    final boolean conditionC = conditionA && conditionB;
    if (conditionC)
    {
        System.out.println(a1 + " and " + b1); // fine
    }
}

为什么testJava2无法编译?编译器报告

variable might not have been initialized

如果conditionb1,则null将为false,因此永远不会在b1块中访问if。为什么编译器不够智能才能检测到它?

0 个答案:

没有答案