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
  • 43,645
  • 9
  • 78
  • 111
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
  • 43,645
  • 9
  • 78
  • 111
2

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

str = str.concat(" game");
actunderdc
  • 1,448
  • 2
  • 11
  • 20