1 Reply Latest reply on Nov 16, 2007 5:31 PM by 796440

    Question about Strings and memory

      Ok, I know that Strings are immutable and everytime you do something like:

      String test = "abc";
      test = test+"def";

      there will be 3 string objects made - abc,def and abcdef. Now if I make String test2 = "abc", does that "abc" come from the memory taken by the first "abc" i created or it is a brand new one?

      Do the strings created (abc,def) gets GCed since there are no more references to them anymore or they just "float around" in the heap?

        • 1. Re: Question about Strings and memory
          If the strings are literals--that is, they're in quotes in your source code--then they live in the constant pool. They're either never GCed, or they're eligible for GC when the class that defined them is unloaded, not sure which. If you refer to the same String literal again, you'll get that same object from the constant pool.

          If the String doesn't come from the constant pool--e.g. read from a file or user input--then it will be eligible for GC when it's no longer reachable, like any other object.