
正文
Java中"String.equals()“和"=="的区别
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
Do NOT use the `==`` operator to test whether two strings are equal! It only determines whether or not the strings are stored in the same location. Sure, if strings are in the same location, they must be equal. But it is entirely possible to store multiple copies of identical strings in different places.
public class Understand_equals
{
public static void main(String[] args)
{
String x = "abcd";
String y = "abcd";
System.out.printf("x = y? %b\n", x == y);
System.out.printf("x.equals(y)? %b\n", x.equals(y));String xx = "abcde";
String yy = new String("abcde");
System.out.printf("xx = yy? %b\n", xx == yy);
System.out.printf("xx.equals(yy)? %b\n", xx.equals(yy));
}
}
输出结果:
x = y? true
x.equals(y)? true
xx = yy? false
xx.equals(yy)? true






