Java – three parameter operators: local variables may not have been initialized
I have the following 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'm using Juno) reports the following errors:
My question is: in this case, should the compiler report that it cannot convert Boolean to string? I understand that the operator = = takes precedence over =, so the compiler should complain about conversion, but that there may be no initialization value
When I change the following lines
System. out. println(test = getValue()== null? “”:test);
to
System. out. println((test = getValue())== null? “”:test);
business as usual.
Editor: I also try to compile it directly using javac It gives the same error
error: variable test might not have been initialized System.out.println(test = getValue() == null ? "" : test);
Solution
The error provided by the compiler is correct According to the operator priority, first evaluate = =, then your ternary operator?: This means that the logic flow is as follows:
getValue() == null
To continue, we assume that the result is wrong The next expression is as follows:
false ? "" : test
The result is a test And our final expression
test = test
But the test was never initialized, so an error occurred