Java:println 中的布尔值(布尔值?“print true":“print false")

2022-01-19 00:00:00 boolean java

我遇到了这种语法:

System.out.println(boolean_variable ? "print true": "print false");

  • 这个带有两个点的语法是什么:调用?
  • 我在哪里可以找到有关它的信息?
  • 它仅适用于布尔值还是以其他不同的方式实现?
  • 推荐答案

    ?: 是条件运算符.(这不仅仅是 : 部分 - 整个方法参数是您示例中条件运算符的一种用法.)

    ? : is the conditional operator. (It's not just the : part - the whole of the method argument is one usage of the conditional operator in your example.)

    它通常被称为三元运算符,但这只是其性质的一个方面 - 具有三个操作数 - 而不是它的名称.如果在 Java 中引入了另一个三元运算符,则该术语将变得模棱两可.之所以称为条件运算符,是因为它有一个 条件(第一个操作数),该条件随后确定对其他两个操作数中的哪一个进行求值.

    It's often called the ternary operator, but that's just an aspect of its nature - having three operands - rather than its name. If another ternary operator is ever introduced into Java, the term will become ambiguous. It's called the conditional operator because it has a condition (the first operand) which then determines which of the other two operands is evaluated.

    计算第一个操作数,然后根据第一个操作数是真还是假来计算任何一个第二个或第三个​​操作数......然后结束up 作为运算符的结果.

    The first operand is evaluated, and then either the second or the third operand is evaluated based on whether the first operand is true or false... and that ends up as the result of the operator.

    所以是这样的:

    int x = condition() ? result1() : result2();
    

    大致相当于:

    int x;
    if (condition()) {
        x = result1();
    } else {
        x = result2();
    }  
    

    重要的是它不评估另一个操作数.例如,这很好:

    It's important that it doesn't evaluate the other operand. So for example, this is fine:

    String text = getSomeStringReferenceWhichMightBeNull();
    int usefulCharacters = text == null ? 0 : text.length();
    

相关文章