Java Interview : Whats the intern method in the String Class in Java?

In any programming language strings are the most used representation for data. From first name to feedback of users all are used in strings. So strings take a lot of memory and repeated use of same string leads to a state where applications might become slower or even start throwing OutOfMemory Errors.
So why not keep these strings in a pool where if a string which is equal to a string in the pool can just use reference to the original string without creating a new string object. So comes the idea of a global String pool, a pool of strings kept in the Permgen space of the memory.
Interning a string simply says that a string is put in a global pool.
  1. String first = "Alpha " + "Beta";
  2. String second = "Alpha " + "Beta";
  3. System.out.println(first == second );
The above code returns true, compiler optimizing the code by pointing both the string reference to the same object.
So what does the intern method does, Intern finds the string in the pool or adds the string to this pool.

Comments

Popular posts from this blog

Java Interview : Threads

Spring Framework Interview Notes : Part Two Wiring

Card Dealer In Java in Less than 5 minutes