As you set the object immutable, we need to create another copy when we change . But here adding zero will not change the value of the object. Therefore, we can return the same object.
Consider the concat() code from String.java for reference:
public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } char buf[] = new char[count + otherLen]; getChars(0, count, buf, 0); str.getChars(0, otherLen, buf, count); return new String(0, count + otherLen, buf); }
As you can see, there is no harm in returning the same object.
source share