How intern() method works in Java

 The intern() returns the value from the string pool if it is there.Otherwise,it adds the value to the string pool.

The string pool also known as the intern pool,is a location in the Java virtual machine that collects the strings.The string pool contains literal values and constants that appear in our program.

String  customerName="hemanth";

Here customerName is a reference variable and we have assigned a value “hemanth” using literal. So it goes into the string pool.

String managerName= new String("hemanth");

Here managerName is a reference variable and we have created a string using new operator. So it does not go into the string pool.

With this knowledge, can you guess what will be the output of the below statement?


String customerName="hemanth";
String managerName= new String("hemanth");
System.out.println(customerName==managerName);// Here == look for //whether the references are referring to the same object or not.

I hope you guessed false. That is great..

Strings are immutable and literals are pooled.The JVM will create only one literal in memory. Let’s see an example.

String customerName = "hemanth";
String managerName = "hemanth";
System.out.println(customerName==managerName);

Now it prints the value “true” because customerName and managerName both point to the same location in memory.

Let’s see another example:

String customerName = "hemanth";
String managerName = " hemanth".trim();
System.out.println(customerName==managerName);

It prints the value “false” because we do not have two of the same String literal. Although customerName and managerName happen to evaluate to the same string, one is computed at runtime. Since it is not the same at compile time, a new String object is created.

Hope you understand the concept of string pool. Now let’s see about intern() method.

The intern() method will use an object in the string pool if one is present. If the literal is not yet in the string pool, Java will add it at this time.

String customerName = "hemanth";
String managerName = new String("hemanth").intern();
System.out.println(customerName==managerName);

Here It prints the value “true”, because we have instructed the compiler to first look into the string pool for the String “hemanth”. There is a literal with “hemanth” in the string pool, So managerName will point to the same.

Things to remember:

The intern() returns the value from the string pool if it is there.Otherwise,it adds the value to the string pool.

"Learning Science shows that learning a bit each day exponentially
improves your ability to retain your knowledge". --- Keep Learning.

 

Comments

Popular posts from this blog

Arrays class usage in Java

About “var” Keyword In Java