Search code examples
javastring-concatenation

Difference between string.concat and the + operator in string concatenation


(This question may be a duplicate but I really didn't understand the other answers)

You have the following code:

String str ="football";
str.concat(" game");
System.out.println(str); // it prints football

But with this code:

String str ="football";
str = str + " game";
System.out.println(str); // it prints football game

So what's the difference and what's happening exactly?


Solution

  • str.concat(" game"); has the same meaning as str + " game";. If you don't assign the result back somewhere, it's lost. You need to do:

    str = str.concat(" game");