Interestingly, the specification of concat
has changed between Java 7 and Java 8.
The Java 7 Specification says:
If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created...
Whereas the Java 8 Specification says:
If the length of the argument string is 0, then this String object is returned. Otherwise, a String object is returned that represents a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.
However, the implementation doesn't seem to have changed. Here is the code.
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
This means that if you use ==
to compare the result of s.concat(" Shukla")
with s3
you will get false
, but this is not strictly speaking guaranteed by the specification.
However, as others have pointed out, you do not need to care about this. You should just compare strings using .equals
and forget about the details.