Use of the intern method of string

Source: Internet
Author: User

Use of the intern method of string

  • public String intern()
    Returns a canonical representation for the string object.

    A pool of strings, initially empty, is maintained privately by the classString.

    When the intern method is invoked, if the pool already contains a string equal to thisStringObject as determined byequals(Object)Method, then the string from the pool is returned. Otherwise, thisStringObject is added to the pool and a reference to thisStringObject is returned.

    It follows that for any two stringssAndt,s.intern() == t.intern()IstrueIf and only ifs.equals(t)Istrue.

    After the intern method is triggered, check whether the JVM runtime pool has a string with the same content as the current string (the equal method is true). If yes, returns a string in the constant pool (external strings are not added to the pool). If such a string does not exist in the pool, the current String object is added to the constant pool and a reference to the string object is returned. The advantage of doing so is to save space ps: If the equal method of two strings is true after comparison (s.equals(t)Istrue), Thens.intern() == t.intern()Istrue
    In Java language specifications, strings defining string text and values of more general constant expressions are internalized so that they can share the same instance. Let's test the following code:

    String s1 = "Hello, Java"; String s2 = "hello," + "Java"; System. out. println (s1 = s2); System. out. println (s1.intern () = s2.intern ());

    The print result is two true values, indicating that the string s1 and s2 share the same instance. Understanding this processing mechanism also helps us understand how to save the memory occupied by these strings when using string constants.
    Example 1:
    Package com. zhb. string. intern; import javax. swing. JOptionPane;/***** @ author Administrator * intern role */public class StringIntern1 {public static void main (String [] args) {String s1, s2, s3, s4, output; s1 = new String ("hello"); s2 = new String ("hello"); if (s1 = s2) output = "s1 and s2 are the same object in memory"; else output = "s1 and s2 are not the same object in memory"; if (s1.equals (s2 )) output + = "\ ns1 and s2 are equal"; else output + = "\ ns1 and s2 are not equal"; s3 = s1.intern (); s4 = s2.intern (); if (s3 = s4) output + = "\ ns3 and s4 are the same object in memory "; else output + = "\ ns3 and s4 are not the same object in memory"; if (s1 = s3) output + = "\ ns1 and s3 are the same object in memory"; else output + = "\ ns1 and s3 are not the same object in memory "; if (s2 = s4) output + = "\ nsand s4 are the same object in memory "; else output + = "\ nsand s4 are not the same object in memory"; if (s1 = s4) output + = "\ ns1 and s4 are the same object in memory"; else output + = "\ ns1 and s4 are not the same object in memory"; System. out. println (output );}}

    The output result is:
    s1   and   s2   are   not   the   same   object   in   memorys1   and   s2   are   equals3   and   s4   are   the   same   object   in   memorys1   and   s3   are   not   the   same   object   in   memorys2   and   s4   are   not   the   same   object   in   memorys1   and   s4   are   not   the   same   object   in   memory


    Example 2:
    Package com. zhb. string. intern; import java. SQL. connection; import java. SQL. resultSet; import java. SQL. statement; import java. util. arrayList; import java. util. list; import com. zhb. util. DBHandler;/***** @ author Administrator * intern function 2 */public class StringIntern2 {static String get () {return "123456789123456789123456789 ";} public static void main (String [] args) throws Exception {// test1 (); // test result: The bus Y memory is: 3260176 // test2 (); // test result: The busy memory is: 2156624test3 (); // test result: The busy memory is: 2152072/** From the above we can find * 1. test2 uses intern, which is much less than the memory occupied by test1 * 2. test3 is a little less than test2, because test3 sets rs. if getString (1) is changed to get () * get (), the returned string is the same as the data record, however, this string exists in the static method of the class *. Therefore, this string is not placed in the runtime pool in the method area, in the local variable table on the Virtual Machine stack *, test3 is less than test2 than the memory of the string in the constant pool. */Long total = Runtime. getRuntime (). totalMemory (); long free = Runtime. getRuntime (). freeMemory (); System. out. println ("The busy memory is:" + (total-free);} public static void test1 () throws Exception {List
       
        
    List = new ArrayList
        
         
    (); Connection conn = DBHandler. getServerConnection (); Statement stmt = conn. createStatement (); ResultSet rs = stmt.exe cuteQuery ("select name from intern"); while (rs. next () {String s = rs. getString (1); Pojo p = new Pojo (); p. setName (s); list. add (p); s = null; p = null;} rs. close (); stmt. close (); conn. close (); System. gc ();} public static void test2 () throws Exception {List
         
          
    List = new ArrayList
          
           
    (); Connection conn = DBHandler. getServerConnection (); Statement stmt = conn. createStatement (); ResultSet rs = stmt.exe cuteQuery ("select name from intern"); while (rs. next () {String s = rs. getString (1); Pojo p = new Pojo (); p. setName (s. intern (); list. add (p); s = null; p = null;} rs. close (); stmt. close (); conn. close (); System. gc ();} public static void test3 () throws Exception {List
           
            
    List = new ArrayList
            
              (); Connection conn = DBHandler. getServerConnection (); Statement stmt = conn. createStatement (); ResultSet rs = stmt.exe cuteQuery ("select name from intern"); while (rs. next () {String s = get (); Pojo p = new Pojo (); p. setName (s); list. add (p); s = null; p = null;} rs. close (); stmt. close (); conn. close (); System. gc ();}}
            
           
          
         
        
       

    /** From the above we can find * 1. test2 uses intern, which is much less than the memory occupied by test1 * 2. test3 is a little less than test2, because test3 sets rs. if getString (1) is changed to get () * get (), the returned string is the same as the data record, however, this string exists in the static method of the class *. Therefore, this string is not placed in the runtime pool in the method area, in the local variable table on the Virtual Machine stack *, test3 is less than test2 than the memory of the string in the constant pool. */

    Conclusion: The Intern method can reduce memory usage. We recommend that you use the intern method to retrieve data from the database.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.