0

(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?

Karol Dowbecki
  • 41,216
  • 9
  • 68
  • 101
Basel Qarabash
  • 11
  • 1
  • 1
  • 7

2 Answers2

4

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");
Karol Dowbecki
  • 41,216
  • 9
  • 68
  • 101
2

The 'concat' function is immutable, so the result of it must be put in a variable. Use:

str = str.concat(" game");
actunderdc
  • 1,386
  • 2
  • 10
  • 19