Search code examples
javaoperatorsstring-concatenation

Java += operator?


I originally learned that

string += otherString; is the same as string = string + otherString;

However, I found that string += char1 + char2 will throw an exception while string = string + char1 + char2 will not. When concatenating chars to strings I typically add an empty string so I don't get the exception, but why is that even necessary?


Solution

  • See this post. The result of adding a char to another char is an int, which cannot be added to the String. Whereas with s = s + c1 + c2, the '+' operator associates left to right so the chars are converted to fit string concatenation.