string intern() method

String intern() method in java is used to get the String from the string pool that is already presented.  Before moving further, we should read about the String literal and how many ways to create a string. In this post we will read the string intern() and how does it work with string pool java.

Here is the table content of the article will we will cover this topic.
1. What is the String intern() method?
2. How does the java string intern() work?
3. String intern() Example Explanation

What is the String intern() method?

It is used to get the string that already presents in the String pool.  As we know whenever we create a string by string literal, the JVM checks the weather the string is present in the string pool or not?
If it presents, then JVM returns the reference of the same string otherwise creates a new string and stores it in the string pool java.
It means when we create a string by string literal, the JVM uses the intern() method.

string intern() method

public: The access modifier of the intern() method is public, so it can be accessed from anywhere.
native:  Here native keyword tells this method is not written in java language, it must be written in another language like C, C++
return type: The return type of method is String.
parameter:  It doesn’t take any parameter.

How does the java string intern() work?

When we create a string by a new keyword, the JVM creates a new string in memory. If we use the intern() method to create a string, then JVM doesn’t create a new string in memory if it is already presented. Let’s take an example and see how the string intern() method works.

public class StringInternExample
{
   public static void main(String args[])
   {
	   String str1 = "Hello";
	   String str2 = new String("Hello");
	   
	   System.out.println("Are both strings same: "+(str1 == str2));
	   
	   String str3 = new String("Hello").intern();
	   System.out.println("Are both strings same: "+(str1 == str3));
   }
}

Output: Are both strings same: false
Are both strings same: true

In above example, you can see when we are using intern() method to get a string.

String intern() Example Explanation

  1. Here we are creating a String str1 by the string literal. The JVM is creating the string in Heap memory and string constant pool.
  2. In the next line, we are creating a new string by using the new operator, the String is created in the heap memory.
  3. In the first print statement, str1 and str2 both are different string because both are referring to different objects.
  4. In the next line, we are creating a new string by use of the intern() method. Now JVM checks whether string in the string pool with value “Hello” is present?  
    Yes, it is presented so it is returning the same object reference.
  5. In the second print statement, str2 and str3 both are the same string because both are referring to the same objects.

Leave a Comment