Monday 16 January 2012

Java : What is an intern() ?

intern() is a method in java String.
JVM has a memory pool for Strings. intern() checks for a entry for the string the particular string in memory pool.
What is a memory pool then ?
When we instantiate a String as String name = "Lucky";  "Lucky" will be into memory pool.
On saying String anotherName = "Lucky", the memory pool will be scanned and the anotherName will be refered to the "Lucky" which was created early.
On saying String nextName = new String("Lucky"); we skip the memory pool scanning and we are creating new instance for the string.
So intern() ?
When we say "Lucky".intern(); the String "Lucky"  is verified with memory pool. If it exists it returns the same string, else it creates an entry in the pool for the same and returns the string.


Some Examples:

  String name1 = "Lucky";
String name2 = new String("Lucky");
System.out.println("Without intern() returns : "+( name1 == name2));
System.out.println("with intern() returns : "+ (name1 == name2.intern()));




No comments:

Post a Comment