java - 条件表达式缺少 Java 错误?

标签 java null if-statement conditional-operator implicit-conversion

使用方法 test1()test2(),我得到一个Type Mismatch Error: Cannot convert from null to int,这是正确的;但为什么我在方法 test3() 中没有得到相同的结果?在这种情况下,Java 如何以不同方式评估条件表达式? (显然,NullPointerException 将在运行时出现)。是遗漏错误吗?

public class Test {

    public int test1(int param) {
        return null;
    }

    public int test2(int param) {
        if (param > 0)
            return param;
        return null;
    }

    public int test3(int param) {
        return (param > 0 ? param : null);
    }

}

提前致谢!

最佳答案

当您混合使用运算符的类型时,条件运算符非常棘手;这是许多人的主题Java Puzzlers .

这是一个经典的例子:

System.out.println(true ? Integer.valueOf(1) : Double.valueOf(2));
// prints "1.0"!!!

还有一个:

System.out.println(true ? '*' : 0);     // prints "*"
int zero = 0;
System.out.println(true ? '*' : zero);  // prints "42"

而且,正如您刚刚发现的那样:

System.out.println(true  ? 1 : null);   // prints "1"
System.out.println(false ? 1 : null);   // prints "null"

了解条件运算符 ?: 的所有错综复杂之处可能非常困难。最好的建议是不要在第二个和第三个操作数中混用类型。

以下引述是Java Puzzlers, Puzzle 8: Dos Equis类(class)的节选:

In summary, it is generally best to use the same type for the second and third operands in conditional expressions. Otherwise, you and the readers of your program must have a thorough understanding of the complex specification for the behavior of these expressions.

JLS 引用

关于java - 条件表达式缺少 Java 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2986796/

相关文章:

java - 未提供身份验证详细信息 REST API POST 请求

if-statement - VHDL 如何在 if 语句中有多个条件

mysql - 在 cgi-bin/test.pl 使用 "ident"时不允许裸字 "strict subs"

java - 带数组字符串的缓冲读取器

java - 在 Scala 中格式化字符串的最佳方式是什么?

java - 与使用普通 JDBC 相比,MyBatis 有什么好处

ruby - 将空字符串就地转换为 nil?

ios - UISwitch 和 viewWithTag 在 numberOfRowsInSection 中为 nil

java - playframework1.2.4中的XSS预防

MySQL 在文件中加载数据 - 将所有列的特定值替换为 null