I have the following piece of code...
import java.util.Random;
public class ThreeArgumentOperator {
private static final Random RANDOM = new Random();
public static void main(String[] args) {
String test;
System.out.println(test = getValue() == null ? "" : test);
}
public static String getValue() {
if (RANDOM.nextBoolean()) {
return "";
} else {
return null;
}
}
}
The Eclipse compiler (I am using Juno) reports the following error:
The local variable test may not have been initialized
My question is: Should not the compiler report in this case that it rather cannot convert boolean to String? I understand that the operator == takes precedence over = and therefore the compiler should complain about the casting, instead it complains about possibly not initialized value.
When I change the following line
System.out.println(test = getValue() == null ? "" : test);
to
System.out.println((test = getValue()) == null ? "" : test);
everything works fine.
EDIT: I have also tried to compile it using javac directly. It gives the same error.
error: variable test might not have been initialized
System.out.println(test = getValue() == null ? "" : test);
The error the compiler is providing you is correct. According to the operator precedence, == will be evaluated first, then your ternary operator ? :. That means, the flow of logic is as follows:
getValue() == null
In order to continue, let's assume the result of this was false. The next expression that follows:
false ? "" : test
The result of this then is test. And our final expression...
test = test
But test was never initialized, hence the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With