[英]Unexpected result in String Comparison In java?
public class HelloWorld {
public static void main(String[] args) {
String s1="yes";
String s2="yes";
System.out.println("-------The result is-----"+ s1==s2);
System.out.println("-------The result is-----"+ (s1==s2));
}
}
Why the above code produce the output 为什么上面的代码产生输出
"false" “假”
-------The result is-----true -------结果是----- true
First of all, you should not be comparing strings with ==
, but with equals()
. 首先,您不应该将字符串与
==
进行比较,而应与equals()
进行比较。
There's also the issue of operator precedence. 还有运算符优先级的问题。 This:
这个:
"-------The result is-----"+ s1==s2
is the same as: 是相同的:
("-------The result is-----"+ s1) == s2
because +
has higher precedence than ==
. 因为
+
优先级高于==
。
when you are comparing strings you should change up ==
to be .equals()
due to the fact that .equals()
compares the contents of the strings to each other or is used to compare objects. 比较字符串时,由于
.equals()
比较字符串的内容或用于比较对象,因此.equals()
==
更改为.equals()
。 ==
checks for reference equality or is used to compare primitives. ==
检查引用是否相等或用于比较基元。 I changed your code below: 我在下面更改了您的代码:
System.out.println("-------The result is-----"+ (s1.equals(s2)));
You are comparing the references of s1
and s2
, and since you defined them separately, they don't have the same references. 您正在比较
s1
和s2
的引用,并且由于分别定义了它们,因此它们没有相同的引用。 To compare the strings, please use equals
or equalsIgnoreCase
要比较字符串,请使用
equals
或equalsIgnoreCase
'+' > '=='
so 所以
"-------The result is-----"+ s1==s2
becomes "-------The result is-----"+ s1==s2
变为
("-------The result is-----"+ s1)==s2
and hence false. ("-------The result is-----"+ s1)==s2
,因此为假。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.