Reputation: 67
I was always told strings in java are immutable, unless your going to use the string builder class or string writter class.
Take a look at this practice question I found online,
Given a string and a non-negative int n, return a larger string that is n copies of the original string.
stringTimes("Hi", 2) → "HiHi"
stringTimes("Hi", 3) → "HiHiHi"
stringTimes("Hi", 1) → "Hi"
and the solution came out to be
Solution:
public String stringTimes(String str, int n) {
String result = "";
for (int i=0; i<n; i++) {
result = result + str; // could use += here
}
return result;
}
As you see in the solution our 3rd line assigns the string , then we change it in our for loop. This makes no sense to me! (I answered the question in another nooby way ) Once I saw this solution I knew I had to ask you guys.
Thoughts? I know im not that great at programming but I haven't seen this type of example here before, so I thought I'd share.
Upvotes: 1
Views: 355
Reputation: 41
If you use Eclipse, you could make a breakpoint and run it step by step. You will find the id (find it in "Variables" View) of "result" changed every time after java did
result = result + str;
On the other hand, if you use StringBuffer like
StringBuffer result = new StringBuffer("");
for(int i = 0; i < n; i++){
result.append(str);
}
the id of result will not change.
Upvotes: 2
Reputation: 726479
The trick to understanding what's going on is the line below:
result = result + str;
or its equivalent
result += str;
Java compiler performs a trick on this syntax - behind the scene, it generates the following code:
result = result.concat(str);
Variable result
participates in this expression twice - once as the original string on which concat
method is called, and once as the target of an assignment. The assignment does not mutate the original string, it replaces the entire String
object with a new immutable one provided by concat
.
Perhaps it would be easier to see if we introduce an additional String
variable into the code:
String temp = result.concat(str);
result = temp;
Once the first line has executed, you have two String
objects - temp
, which is "HiHi"
, and result
, which is still "Hi"
. When the second line is executed, result
gets replaced with temp
, acquiring a new value of "HiHi"
.
Upvotes: 4
Reputation: 320
String objects are indeed immutable. result
is not a String, it is a reference to a String object. In each iteration, a new String object is created and assigned to the same reference. The old object with no reference is eventually destroyed by a garbage collector. For a simple example like this, it is a possible solution. However, creating a new String object in each iteration in a real-world application is not a smart idea.
Upvotes: 1