Consider body of a class which has only these methods:
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
}
}
Why does testJava2
fail to compile? The compiler reports
variable might not have been initialized
The condition
will be false if b1
was null
, so b1
would never be accessed within the if
block. Why isn't the compiler smart enough to detect that?