Reputation: 1599
Studying for OCAJ7
I know String objects are immutable. I know using methods like .concat()
on a String object will just create a new String object with the same reference name. I'm having a hard time, however, with wrapping my head around the following:
String str1 = "str1";
String str2 = "str2";
System.out.println( str1.concat(str2) );
System.out.println(str1);
// ouputs
// str1str2
// str1
String str3 = "fish";
str3 += "toad";
System.out.println(str3);
// outputs
// fishtoad
If strings are immutable, why does using +=
to concatenate affect the original String object, but .concat()
does not? If I only want a String to concatenate with using +=
, is using String
better than using StringBuilder
, or vice versa?
Upvotes: 2
Views: 130
Reputation: 1785
Above you are not changing the reference of str1
in System.out.println(str1.concat(str2) )
so it is temporary storing the reference of str1.concat(str2)
.
But in str3+=str4
whole reference get moved to "fishtoad" therefore it get changed.But again if you defined a string str5="fish"
then it reference back to previous location which was referencing by str3
.
Upvotes: 0
Reputation: 1004
concat() method creates a new string. You have to remember that Strings in Java are immutable.
str1 will point to the newly created string if the o/p is assigned to it,
str1 = str1.concat(str2);
otherwise str1 continues to point to the old string.
If you are going to concat multiple strings together in a loop, then it is better to use StringBuilder
Upvotes: 0
Reputation: 340
What's happening here is that String.concat(String);
does not actually combine str1
and str2
together, instead it returns a new String object that is equivalent to str1str2
. When you use str1 += str2
, you are actually combining the variables, and then putting the value into str1
.
Upvotes: 1
Reputation: 1734
Yes you are right Strings are immutable.
But when you write str1.concat(str2)
inside System.out.println() you are printing the result returned by the concat() function.The result is a new String which is outputted on the console.
You haven't assigned the value to str1.
But when you write +=
you are first concatenating something to the String the then assigning the reference back to str1
.
This explains the output.
Upvotes: 1
Reputation: 178263
The concat
method is more like +
than +=
. It returns the new string; it doesn't modify the original string or the argument (String
s are immutable).
str1.concat(str2)
is equivalent to str1 + str2
, so str1
isn't modified, and the result is discarded.
However, +=
also assigns the result back to the left side, and str3
now refers to the new string. That's the difference.
Upvotes: 1
Reputation: 6960
str3 += "toad" means
str3 = str3 + "toad";
So you concatenate and assign the result back to str3
Upvotes: 0
Reputation: 240898
because you are catching the reference of newly generated String instance in str3
str3 += "toad";
is
str3 = str3 + "toad"
Upvotes: 3