gpt4 book ai didi

java - Java 中的 boolean 函数

转载 作者:行者123 更新时间:2023-11-29 09:43:48 24 4
gpt4 key购买 nike

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,所有这些都依赖于运算符的优先级。

在 Java 中,+ 优先于 ==

这意味着 2 实际上“读取”:

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

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

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

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?

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

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

在 5 中,由于字符串连接, boolean 值被自动装箱。

6 再次依赖于 2 中提到的运算符优先级;这次是字符串 true + ""+ s1 ,它是(引用)与 s2 相比(并且给出 false)。请参阅 5 以了解 true 会发生什么。

关于java - Java 中的 boolean 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22526170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com