sumit amble sumit amble - 15 days ago 6
Java Question

In string what happens to the string when we concat other string to it where is the first string

String immutability
while reviewing string i came across this question

public class AnotherTest {
public static void main(String[] args) {
String str = "hello ";
str = str.concat("java");

}
}


now the str has value
"hello java"
but what happens to first value
"hello"
as
String
is immutable is it still remains there in heap or garbage collected

Answer

It might still remain on the heap if it's reference is still kept somewhere. Otherwise it should be garbage collected.

In your example it will be garbage collected. However in the following one it will remain on the heap:

public class AnotherTest {
    public static void main(String[] args) {
        String str = "hello ";
        String str2 = str;
        str = str.concat("java");
        System.out.println(str2);
    }
}

will simply print "hello ".

An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.

--reference

According to the quotation it cannot change but it can be used. String#concat method uses characters of the instance on which the method is called. It also takes characters of another instance of String class and then creates new String with characters of both instances in a certain order.

I think I know what is still unclear to the OP.

Returns: a string that represents the concatenation of this object's characters followed by the string argument's characters.

--Reference
is quite misleading. If I wrote the documentation, I would write:

Returns: a new string that represents the concatenation of this object's characters followed by the string argument's characters.

This would be easier for beginners to understand. However this is guaranteed by String`s immutability so the new is not necessary in the documentation.