Export (0) Print
Expand All
Expand Minimize

java.lang.String.intern()

Places a String in the global string pool. This table maintains a single reference to each unique String ever created by an instance of the runtime in order to optimize space.


public String intern()

An interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added.

// string_intern.jsl

public class Program
{
    public static void main(String[] args)
    {
        // Create three strings in three different ways.
        String s1 = "J# Sample";
        String s2 = new StringBuffer("J#").append(" Sample").toString();
        String s3 = s2.intern();

        // Determine which strings are equivalent using the ==
        // operator (as compared to calling equals(), which is
        // a more expensive operation.
        System.out.println("s1 == s2? " + (s1 == s2));
        System.out.println("s1 == s3? " + (s1 == s3));
    }
}

/*
Output:
s1 == s2? false
s1 == s3? true
*/

Community Additions

ADD
Show:
© 2014 Microsoft