4

Possible Duplicate:
When to use intern()
When should we use intern method of String?

Does java intern strings automatically ? If it does why does string have an explicit intern method ? Any particular use cases when an explicit call is needed ?

Community
  • 1
  • 1
Vinoth Kumar C M
  • 10,378
  • 28
  • 89
  • 130

3 Answers3

1

Java does not intern strings created at run-time automatically. (It does do so for string constants at compilation time).

I had a specific use case where I saved ~30% of heap used in a component that was receiving records expressed in a map. The set of keys in each record were identical, yet every new record received created a new instances of the key strings. By interning the key strings, heap consumption was greatly reduced.

David J. Liszewski
  • 10,959
  • 6
  • 44
  • 57
  • An answer to another question also describes "when to intern" http://stackoverflow.com/a/1855195/55452 – David J. Liszewski May 05 '12 at 13:51
  • But my question is why we use `new String("exm")` and force to check `intern()` method to save `heap memory` as you say ? If we use literals like `String s1 = "ex1" ; String s2 = "ex1";` So both are refer same object (s1==s2) so there is no need call 'intern()' method here . – HybrisHelp Jul 26 '13 at 05:57
0

From JavaDoc: "All literal strings and string-valued constant expressions are interned."

Interning at runtime does not offer any performance advantages as far as I know. It can safe you some heap space, if you have many dynamically created string, which contain duplicates. Using your own hash for instance for this seems safer to me, though.

Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85
0

It only interns string literals automatically. If you create the string on your own (from an input stream from the network, for instance), it won't be interned. If you expect there to be a lot of instances of that same string, it may be worthwhile and interning them, rather than having lots of equivalent strings on the heap. Personally, I've never use it.

yshavit
  • 42,327
  • 7
  • 87
  • 124