我有以下代码......
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;
}
}
}
Eclipse编译器(我正在使用Juno)报告以下错误:
本地变量测试可能尚未初始化
我的问题是:在这种情况下,编译器是否应该报告它无法将boolean
转换为String
?我理解运算符==
优先于=
,因此编译器应该抱怨转换,而是抱怨可能没有初始化值。
当我更改以下行
时 System.out.println(test = getValue() == null ? "" : test);
到
System.out.println((test = getValue()) == null ? "" : test);
一切正常。
编辑:我还尝试直接使用javac
编译它。它给出了同样的错误。
error: variable test might not have been initialized
System.out.println(test = getValue() == null ? "" : test);
答案 0 :(得分:5)
编译器为您提供的错误是正确的。根据运算符优先级,首先评估==
,然后评估您的三元运算符? :
。这意味着,逻辑流程如下:
getValue() == null
为了继续,我们假设结果为false
。接下来的表达式是:
false ? "" : test
这样的结果是test
。我们最后的表达......
test = test
但test
从未初始化,因此错误。
答案 1 :(得分:2)
我真的不明白问题出在哪里。第一个表达是
test = getValue() == null ? "" : test
这意味着:test
初始化为
getValue()
返回null test
否则由于测试尚未初始化,因此无法使用自身初始化test
,因此会显示错误消息。
第二个表达是
(test = getValue()) == null ? "" : test
表示:
test
getValue()
test
与null
test
为null,则表达式求值为空字符串test
为什么不编译?
答案 2 :(得分:0)
这对我来说很有意义。
第二个编译版本实际上是两个单独的语句。它相当于这段代码:
test = getValue();
System.out.println(test == null ? "" : test);
第一个为test
分配值:
test = getValue();
现在test
有一个值。如果test
不为空,则第二个语句能够确定经历结果值。
第一个非编译版本是一个语句,由于test
尚无值,因此分配test
(即test
)的值未知。