Does == check for full equality in Booleans? - Java(== 检查布尔值是否完全相等?- 爪哇)
问题描述
所以我听说如果我将 2 个字符串与 == 进行比较,那么只有当它们都引用同一个对象/实例时,我才会返回 true.那是字符串.布尔值呢?
So I've heard that if I compare 2 strings with == then I will only get true back if they both refer to the same object/instance. That's strings. What about Booleans?
推荐答案
== 检查布尔值是否完全相等?- 爪哇
Does == check for full equality in Booleans? - Java
这取决于您是在谈论 Boolean
s(对象包装器,注意大写 B
)还是 boolean
s(原语,注意小写 b
).如果您谈论的是 Boolean
s(对象包装器),与所有对象一样,==
会检查 identity,而不是 等价.如果您在谈论 boolean
s(原语),它会检查是否等价.
It depends on whether you're talking about Boolean
s (the object wrapper, note the capital B
) or boolean
s (the primitive, note the lower case b
). If you're talking about Boolean
s (the object wrapper), as with all objects, ==
checks for identity, not equivalence. If you're talking about boolean
s (primitives), it checks for equivalence.
所以:
Boolean a, b;
a = new Boolean(false);
b = new Boolean(false);
System.out.println("a == b? " + (a == b)); // "a == b? false", because they're not the same instance
但是
boolean c, d;
c = false;
d = false;
System.out.println("c == d? " + (c == d)); // "c == d? true", because they're primitives with the same value
<小时>
关于字符串:
Regarding strings:
我听说如果我将 2 个字符串与 == 进行比较,那么只有当字符串相同并且它们都引用相同的对象/实例时,我才会返回 true...
I've heard that if I compare 2 strings with == then I will only get true back if the strings are identical and they both refer to the same object/instance...
这不是真正的与":==
将仅检查两个 String
变量是否引用相同的 String
实例.当然,一个 String
实例只能有一组内容,所以如果两个变量都指向同一个实例,那么内容自然是相同的... :-) 关键是 ==
将报告 不同 String
实例的 false
,即使它们具有相同顺序的相同字符.这就是为什么我们在它们上使用 equals
,而不是 ==
.由于 intern
ing,特定于字符串(Boolean
没有等价物,尽管当您使用 Boolean.valueOf(boolean)
,你会得到一个缓存的对象).另请注意,Java 不像原始 boolean
、int
等那样具有原始字符串.
It's not really an "and": ==
will only check whether the two String
variables refer to the same String
instance. Of course, one String
instance can only have one set of contents, so if both variables point to the same instance, naturally the contents are the same... :-) The key point is that ==
will report false
for different String
instances even if they have the same characters in the same order. That's why we use equals
on them, not ==
. Strings can get a bit confusing because of intern
ing, which is specific to strings (there's no equivalent for Boolean
, although when you use Boolean.valueOf(boolean)
, you'll get a cached object). Also note that Java doesn't have primitive strings like it does primitive boolean
, int
, etc.
这篇关于== 检查布尔值是否完全相等?- 爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:== 检查布尔值是否完全相等?- 爪哇


- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01