三个参数运算符:局部变量可能尚未初始化

时间:2012-12-15 17:37:59

标签: java eclipse javac

我有以下代码......

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);

3 个答案:

答案 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()
  • testnull
  • 进行比较
  • 如果test为null,则表达式求值为空字符串
  • 否则评估为test
  • 的值

为什么不编译?

答案 2 :(得分:0)

这对我来说很有意义。

第二个编译版本实际上是两个单独的语句。它相当于这段代码:

test = getValue();
System.out.println(test == null ? "" : test);

第一个为test分配值:

test = getValue();

现在test有一个值。如果test不为空,则第二个语句能够确定经历结果值。

第一个非编译版本是一个语句,由于test尚无值,因此分配test(即test)的值未知。