6

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?

Artanis
  • 561
  • 1
  • 7
  • 26
  • 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. – Elliott Frisch Dec 20 '18 at 21:34
  • Seems like string literals are put into string pool and remain in memory as long as program is running. – Artanis Dec 20 '18 at 21:55
  • @ElliottFrisch I think you'll have to go back quite some way to find string literals not being interned. – Tom Hawtin - tackline Dec 20 '18 at 22:45
  • @Zeratul Or the class loader collected. – Tom Hawtin - tackline Dec 20 '18 at 22:46
  • @ElliottFrisch There’s no point in preferring `StringBuilder` over `StringBuffer` any more. If only used in one thread, the compiler will elide the locking used in `StringBuffer`, so it won’t make any difference (as a matter of habit, I use `StringBuilder` too). – Ole V.V. Dec 21 '18 at 03:33
  • 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. – Holger Dec 21 '18 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. – Holger Dec 21 '18 at 16:43

2 Answers2

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.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
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

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142