关于Java等于运算符的用法 [英] On the usage of Java equality operator
问题描述
可能重复:
如何比较Java中的字符串?
class StringTest {
public static void main(String[] args) {
String str1 = "Hi there";
String str2 = new String("Hi there");
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
}
输出结果:
False
true
为什么即使str1和str2看起来相等,第一个输出也是假的?
Why the first output is false even when the str1 and str2 appear to be equal?
推荐答案
==
比较变量的内容。 (你很清楚 intA == intB
。)
==
compares content of variables. (You know this very well from intA == intB
.)
A String
变量包含引用到 String
对象,所以 ==
将比较参考。
A String
variable contains a reference to a String
object, so ==
will compare references.
之后
String str1 = "Hi there";
String str2 = new String("Hi there");
str1
和 str2
将引用不同的字符串对象,因此包含不同的引用,因此 str1 == str2
将产生 false
。
str1
and str2
will refer to different string objects, thus contain different references, so str1 == str2
will yield false
.
str1.equals(str2)
另一方面将比较<$的对象c $ c> str1 和 str2
是指,正如您所指出的那样,产生 true
。
str1.equals(str2)
on the other hand will compare the objects that str1
and str2
refers to, which, as you have noted, yields true
.
这篇关于关于Java等于运算符的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!