Java 中的布尔函数

2022-01-19 00:00:00 string boolean java println
String s1="hi";
String s2="hi";

boolean b1 = true;
boolean b2 = false;

(1) System.out.println(s1==s2);                            //true
(2) System.out.println(s1==s2 + s1==s2);                   //false
(3) System.out.println(s1==s2+ " " + s1==s2);              //false

(4) System.out.println(b1+b2);                             //error : bad operand types
(5) System.out.println(b1 + " " + b2);                     //true false
(6) System.out.println(true +" "+ s1==s2);                 //false

  • (2) & 有什么区别?(4)?
  • (3) & 有什么区别?(5)?
  • 为什么它在 (3) &(6)?
  • 推荐答案

    除了4之外,都是依赖运算符优先级的.

    Except for 4, all of these rely on operator precedence.

    在 Java 中,+ 优先于 ==.

    And in Java, + has precedence over ==.

    这意味着 2 次实际读取":

    Which means 2 actually "reads":

    s1 == ((s2 + s1) == s2)
    

    因此,第一个 == 的右侧操作数是一个布尔表达式,它将两个对象引用相互比较(事实上它们都是 String 的事实是不相关),在这里它们是不一样的.因此右侧操作数是布尔值false.

    Therefore the right side operand of the first == is a boolean expression which compares two object references to one another (the fact that they are both Strings here is irrelevant) and here they are not the same. Hence the right side operand is boolean false.

    但是由于左侧操作数是String,并且由于==不适用于操作数Stringboolean,这会产生编译错误.JLS,第 15.21 节:

    But since the left side operand is a String, and since == is not applicable to operands String and boolean, this gives a compile error. JLS, section 15.21:

    相等运算符可用于比较两个可转换(第 5.1.8 节)为数值类型的操作数,或两个布尔或布尔类型的操作数,或两个均为引用类型或空类型的操作数.所有其他情况都会导致编译时错误.

    The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error.

    如果这真的为你编译,你正在使用一个错误的 Java 编译器,它将右侧操作数自动装箱为 Boolean,这是不应该的.让我猜猜:Eclipse 的 ECJ?

    If this really compiles for you, you are using a buggy Java compiler which autoboxes the right side operand to a Boolean, which it shouldn't. Let me guess: Eclipse's ECJ?

    4 是一个错误,因为 + 运算符不接受 booleans 作为操作数.

    4 is an error since the + operator doesn't accept booleans as operands.

    3 读起来几乎和 2 一样,只是这次是 s2 + " " + s1,它(试图)与 s2 相比.由于同样的原因,它无法编译.

    3 reads nearly the same as 2, except that this time it is s2 + " " + s1 which is (attempted to be) compared to s2. It fails to compile for the same reason.

    在 5 中,由于字符串连接,布尔值被自动装箱.

    In 5, booleans are autoboxed because of string concatenation.

    6 再次依赖于 2 中提到的运算符优先级;这次是字符串 true + " " + s1s2 相比(参考)(并且给出错误).请参阅 5 了解 true 会发生什么.

    6 again relies on the operator priority mentioned in 2; this time it is string true + " " + s1 which is (reference) compared with s2 (and that gives false). See 5 for what happens to true.

相关文章