Interning of String in Java


String interning is a process wherein a single copy of every distinct string value is stored. In addition to this, the strings can’t be changed too. This way, strings can contain the same data as well as share the same memory. This way, the memory required would be greatly reduced.

When the ‘intern’ function is called −

  • It checks the equality between two strings- whether the string object is present in the String Constant pool (SCP) or not.

  • If available, the string is returned by fetching it from the pool. Otherwise, a new String object is created and added to the pool. A reference to this String Object is also returned.

  • If for two strings ‘a’, and ‘b’, a.intern() == b.intern() is true iff a.equals(b) returns true.

Let us see an example −

Example

 Live Demo

public class Demo{
   public static void main(String[] args){
      String s1 = new String("Its");
      String s2 = s1.concat("sample");
      String s3 = s2.intern();
      System.out.println("Checking equality of object 2 and 3 :");
      System.out.println(s2 == s3);
      String s4 = "Its a sample";
      System.out.println("Checking equality of object 3 and 4 :");
      System.out.println(s3 == s4);
   }
}

Output

Checking equality of object 2 and 3 :
true
Checking equality of object 3 and 4 :
false

A class named Demo contains the main function. Here three instances of String objects are defined, wherein the second string is a concatenation of first string with a different value. The third string is a function call to ‘intern’ on the second string. These strings are compared using the ‘==’ operator and result is displayed on the console.

Updated on: 04-Jul-2020

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements