布尔功能在Java中 [英] Boolean Functionality in Java

查看:111
本文介绍了布尔功能在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,所有这些依赖于运营商precedence。

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

    和在Java中, + 有precedence超过 ==

    And in Java, + has precedence over ==.

    这意味着2实际上是读

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

    因此​​,第一个的右侧操作数== 是布尔前pression这两个对象引用比较彼此(事实上,它们都是字符串在这儿是不相关的),并在这里,他们是不一样的。因此,右侧操作数是布尔

    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.

    但由于左侧操作数是字符串,自 == 并不适用于操作数字符串布尔,这给编译错误。 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)为数值型,或boolean类型或布尔的两个操作数或两个操作数是每一个参考值类型或空类型。所有其他情况导致编译时错误。

    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编译器这autoboxes右侧操作数为布尔,它不应该。让我猜猜: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是一个错误,因为 + 运营商不接受布尔取值作为操作数。

    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,布尔是因为字符串连接autoboxed。

    In 5, booleans are autoboxed because of string concatenation.

    6再次依赖于2中提到的操作者优先;这一次却是字符串真++ S1 这是(参考)与 S2 相比(以及提供虚假)。见5会发生什么真正

    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.

    这篇关于布尔功能在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆