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?

2
  • 2
    You didn't assign str.concat(" game"); to a variable, so str still has its original value. Commented May 31, 2018 at 14:44
  • Strings are imutable, so you have to assing str.concat(" game"); to a variable Commented May 31, 2018 at 14:46

2 Answers 2

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");
Sign up to request clarification or add additional context in comments.

2 Comments

So what happened exactly is the following? : str.concat(" game") created a new string object "football game" But it didn't change the str reference, and str still refer to "football"
@BaselQarabash yes
2

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

str = str.concat(" game");

1 Comment

Just a small thing: Strings are imutable, not the concat function

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.