1

As we know Strings are immutable. But what happens to the reference of a string object if we replace them.

Please check the below example

public class Test {

    public static void main(String[] args){

        String s = "My name is Java"; -------> Step 1
        s = s.replace("Java", "Python"); ---> Step 2
        System.out.println(s);
    }

}

In step one, Reference s pointing to object "My name is Java", but after replace its s is pointing to "My name is Python".

After replace who is pointing to "My name is Java" ?

linuxman
  • 51
  • 8
  • @rmlan, Is there any way I could hook up that same object "My name is Java" with any other reference ? – linuxman Jan 10 '18 at 14:28
  • 1
    @linuxman not after you've removed the last reference to it. If you had `String s2 = s;` _before_ the call to `s.replace` you could, but once you've overwritten the reference, it's gone. – Mike Harris Jan 10 '18 at 14:32
  • @rmlan Well, correct me please but that is a string literal and will exist in the string pool until the shutting down the JVM!? I am sure that you can reference the string again by "String str = "My name is Java"". what am I missing? – Jack Flamp Jan 10 '18 at 14:54
  • You can reference to it again with String x = "My name is Java", if it is still in the String Pool. That's the case if garbage collection did not already take place. s.replace gives you a new String (new reference to "My name is Python"). – Chris311 Jan 10 '18 at 15:01
  • @JackFlamp - that's a good point actually. I was too quick to respond. With few exceptions, String literals are interned in the String pool automatically and therefore are not candidates for garbage collection. – rmlan Jan 10 '18 at 15:47
  • What @JackFlamp has said is absolutely correct, and you could "hook up" to that same String object by simply using the same _exact_ String literal at a later point in code. See https://stackoverflow.com/questions/18406703/when-will-a-string-be-garbage-collected-in-java for more. – rmlan Jan 10 '18 at 15:49

0 Answers0