7

example code:

StringBuffer sb = new StringBuffer("hi");
sb = null;

Question:

will the literal string "hi" somehow stay in memory, even after the StringBuffer has been garbage collected? Or is it just used to create a char array for the StringBuffer and then never put anywhere in memory?

7
  • 1
    Prefer StringBuilder to StringBuffer. As for the literal String, it depends on your version of Java and whether or not it's in the intern pool. Commented Dec 20, 2018 at 21:34
  • Seems like string literals are put into string pool and remain in memory as long as program is running. Commented Dec 20, 2018 at 21:55
  • @ElliottFrisch I think you'll have to go back quite some way to find string literals not being interned. Commented Dec 20, 2018 at 22:45
  • 1
    @OleV.V. well, there’s a difference between waiting for the optimizer to remove an unnecessary operation and not requesting the operation in the first place. So regardless of how tiny the difference might be, due to the absence of any other functional difference, there’s still a reason to prefer StringBuilder. After all, you have to decide for either. Commented Dec 21, 2018 at 16:41
  • 1
    The StringBuffer will copy the argument passed to its constructor, but does not hold any reference to it, hence, whether it gets garbage collected or not, is entirely irrelevant to the life cycle of the "hi" string instance. Commented Dec 21, 2018 at 16:43

2 Answers 2

10

Yes, hi is a compile time constant so it gets interned by the compiler and resides in the string pool.

Moreover G1GC can perform String deduplication as part of JEP 192: String Deduplication in G1 in which case even if hi wasn't interned by javac it might be retained as part of the deduplication.

Sign up to request clarification or add additional context in comments.

Comments

4

A string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

JLS 11 > 3. Lexical Structure > 3.10.5. String Literals

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.