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
", x == y);
		System.out.printf("x.equals(y)? %b
", x.equals(y));

		String xx = "abcde";
		String yy = new String("abcde");
		System.out.printf("xx = yy? %b
", xx == yy);
		System.out.printf("xx.equals(yy)? %b
", xx.equals(yy));
	}
}

输出结果:

x = y? true
x.equals(y)? true
xx = yy? false
xx.equals(yy)? true
原文地址:https://www.cnblogs.com/yaos/p/7084176.html