Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Use of intern() of string in Java

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 256
    Comment on it

    String.intern() has a great importance in java. We can use String.intern() to deal with String duplication problem in Java. A string is said to be duplicate if it contains the same content as another string but has a different memory location e.g. string1 != string2 but string1.equals(string2) is true. By using the intern() method we can save a lot of memories consumed by duplicate String instances.


    As in average java application string objects consumes large amount of heap memory that is the reason we should use intern() method so that the duplication can be reduced. The intern() method can be used to intern a String object and store them into String pool for further reuse.

    For example, when you create a String literal e.g. "abc", it's automatically stored inside String pool, but when you create a new String object e.g. new String("abc"), even though it's same String, a new object at a different memory location is created.

    Now the duplicate String is created and when the intern() method on this object is called the JVM automatically puts this String in the pool and if someone creates the "abc" object then instead of creating new object this old object is returned. Thus, in this way it helps us in saving lot of memory.

    SYNTAX: Here is the syntax of this method:

    public String intern()

    EXAMPLE:

      import java.io.*;
    
      public class ABC{
      public static void main(String args[]){
      String Stg1 = new String("Welcome to evontech.com");
      String Stg2 = new String("WELCOME TO EVONTECH.COM");
    
      System.out.print("Canonical representation:" );
      System.out.println(Stg1.intern());
    
      System.out.print("Canonical representation:" );
      System.out.println(Stg2.intern());
       }
     }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: