intern() in java {Quick Read}

Anubhav
1 min readMay 19, 2021

A few days back, I was reading about memory management in java. And there I got to know about Permanent Generation(PemGem). Before reading the article, I was already aware that string literals are stored in a pool(blah blah blah). And I used to believe it was on heap space.

After I finished reading, I got to know I was wrong. That string pool is stored in Permanent Generation space. Which is fairly small and separate from heap space.

But what it has to do with intern()?

Nothing much it is just good to know :)

  • intern() allows you to check whether a string literal exists in the pool, if it does then simply return the reference to it and if it doesn’t then create an object in string constant pool and return the reference.
  • This means every time you try to reference a string literal, you are going to reference the same object.
  • You don’t have to call this method explicitly, because this method is called implicitly on string literals.
String s1 = new String(“Hello World”);

But when you create a string using new keyword, then 2 objects gets created

1- in heap space (this is the reference, you are going to hold)

2- in PemGem(String constant pool)

String s2 = “Hello World”;// another wayString s3 = s1.intern();

So if you want to save some memory, just directly use string literals rather than calling new keyword.

--

--