看,这是一个棘手的概念。
两者之间有区别:
// These are String literals
String a = "Hiabc";
String b = "abc";
String c = "abc";
和
// These are String objects.
String a = new String("Hiabc");
String b = new String("abc");
String c = new String("abc");
如果你的字符串是对象,即
String b = new String("abc");
String c = new String("abc");
然后,两个不同的对象将在字符串池中的两个不同内存位置创建并执行
b == c
会产生false。
但由于您的 String b 和 String c 是文字,
b == c
结果true。这是因为没有创建两个不同的对象。 a 和 b 都指向堆栈内存中的相同字符串。
这就是区别。你是对的,== 比较内存位置。这就是原因,
a.substring(2, 5) == b; // a,substring(2, 5) = "abc" which is at the location of b, and
b == c // will be true, coz both b and c are literals. And their values are compared and not memory locations.
为了在String pool 和NOT stack memory 中拥有两个具有相同值但位于不同位置的单独字符串,您需要创建如上所示的字符串对象。
所以,
a.substring(2, 5) == b; // and
b == c; // will be false. as not both are objects. Hence are stored on separate memory locations on the String pool.
你必须使用
a.substring(2, 5).equals(b);
b.equals(c);
如果是对象。