This question has been asked before, but not really answered.
If the substring method creates a new object, and this is object is "interned" in the pool, then why does the ==
return false. Here's my code:
public class StringTest {
public static void main(String[] args) {
String str1 = "The dog was happy";
String str2 = "The hog was happy";
System.out.println(str1.substring(5));// just to make sure
System.out.println(str2.substring(5));
if (str1.substring(5) == str2.substring(5)) {
System.out.println("Equal using equality operator");
} else {
System.out.println("Not equal using equality operator");
}
if (str1.substring(5).equals(str2.substring(5))) {
System.out.println("Equal using equals method");
} else {
System.out.println("Not equal using equals method");
}
}
}
Output is: 1. og was happy 2. og was happy 3. Not equal using equality operator 4. Equal using equals method
P.S. This is the substring method source code:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
P.S. This question has been marked as asked and answered by several people, yet I could not find one single instance on Stack Overflow where someone actually explained why substring(0) will evaluate to true.