class helloworld
{
public static void main(String args[]) {
String str1="hello";
String str2="world";
String str=str1+str2;
str.intern();
System.out.println(str=="helloworld");
}
}
o/p:假
执行程序后,它会生成 false 作为输出。如果使用 equals() 而不是 "==",则返回 true。为什么会这样?
2.在这种情况下,更改类名后,它会生成 true 作为输出。
class main
{
public static void main(String args[]) {
String str1="hello";
String str2="world";
String str=str1+str2;
str.intern();
System.out.println(str=="helloworld");
}
}
o/p:true
为什么使用 "==" 与类名进行黑白中间字符串比较时会出现矛盾(如果比较字符串名称用作类名)?
最佳答案
原因是在第一个示例中,字符串“helloworld”已经在字符串池中,因为它是类的名称。所以实习它不会向字符串池添加任何内容。因此 str
不会是中间值,并且比较将为 false。
在第二个示例中,str.intern()
实际上将 str
添加到字符串池中,因为 "helloworld"
尚不存在。然后,当遇到 "helloworld"
文字时,实际使用的字符串对象是字符串池中的字符串对象。这只是 str
,因此比较结果为真。
关于java - 为什么类名与使用 "=="进行的实习字符串比较相矛盾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19653165/