1

I have made the code but please tell the functionality of the intern() method of String class , does it try to bring the pool object address and memory address on the same page?

I have developed the below code :

    public class MyClass
    {   
         static String s1 = "I am unique!";
         public static void main(String args[])
         {
            String s2 = "I am unique!";
            String s3 = new String(s1).intern();// if intern method
 is removed then there will be difference
          // String s3= new String("I am unique!").intern(); 

            System.out.println("s1 hashcode -->"+s1.hashCode());
            System.out.println("s3 hashcode -->"+s3.hashCode());
            System.out.println("s2 hashcode -->"+s2.hashCode());
            System.out.println(s1 == s2);
            System.out.println("s1.equals(s2) -->"+s1.equals(s2));
            /* System.out.println("s1.equals(s3) -->"+s1.equals(s3));
             System.out.println(s1 == s3);
            System.out.println(s3 == s1);
            System.out.println("s3-->"+s3.hashCode());*/
        //  System.out.println(s3.equals(s1));
        }
    }

Now what's the role of the above intern() method?

As the hashCodes() are the sames, please explain the role of intern() method.

Thanks in advance.

alain.janinm
  • 19,951
  • 10
  • 65
  • 112
dghtr
  • 561
  • 3
  • 6
  • 20
  • `s1` and `s2` are references to the same string - is that deliberate? It would help if you'd say what you expected the results to be (ideally without all the commented out code...) – Jon Skeet May 01 '12 at 07:36

5 Answers5

1

Since operator== checks for identity, and not equality, System.out.println(s1 == s3); (which is commented out) will yield true only if s1 and s3 are the exact same objects.

The method intern() makes sure that happens, since the two strings - s1 and s3 equal each other, by assigning their intern() value, you make sure they are actually the same objects, and not two different though equal objects.

as the javadocs say:

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

p.s. you do not invoke intern() on s1, because it is a String literal - and thus already canonical.

However, it has no affect on s1 == s2, since they are both string literals, and intern() is not invoked on neither of them.

amit
  • 175,853
  • 27
  • 231
  • 333
0

This method returns a canonical representation for the string object. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

Returns a canonical representation for the string object.

refer http://www.tutorialspoint.com/java/java_string_intern.htm

If you call the intern method of this String object,

str = str.intern();

The JVM will check whether the String pool maintained by the JVM contains any String objects with the same value as the str object with the equals method returning true.

If the JVM finds such an object, then the JVM will return a reference to that object present in the String pool.

If no object equal to the current object is present in the String pool, then the JVM adds this string into the String pool and returns its reference to the calling object.

The JVM adds the object to the String pool so that the next time when any string object calls the intern method, space optimization can be done if both of these strings are equal in value.

You can check the working of intern method using the equals and == operators.

refer : http://java-antony.blogspot.in/2007/07/string-and-its-intern-method.html

Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
0

From the String.intern() Javadoc

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

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.

Returns: a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

Do you have a more specific doubt which is not covered by the Javadoc?

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

.intern() ensures that only one copy of the unique String is stored. So, multiple references to the same interned String will result in the same hashCode() as the hashing is being applied to the same String.

user1367351
  • 102
  • 2
  • Just a note of caution, interning a String places it in PermGen..If you're not careful you could run out of PermGen and throw an OutOfMemoryError. – user1367351 May 01 '12 at 07:45
  • Interestingly, the String pool is garbage collected, too. So if you intern a String that is not also a literal, and drop any reference to the interned String, the interned String can be GC'ed, as seen in this answer: http://stackoverflow.com/a/2433076/282229 – Christian Semrau May 01 '12 at 08:11
0

String.intern() canonicalize strings in an internal VM string pool. It ensure that there is only one unique String object for every different sequence of characters. Then those strings can be compare by identity (with operator ==), instead of equality (equals()).

For example :

public class Intern{
    public static void main(String[]args){
        System.out.println(args[0].equals("")); //True if no arguments

        System.out.println(args[0] == ""); //false since there are not identical object

        System.out.println(args[0].intern() == ""); //True (if there are not multiple string tables - possible in older jdk)
    }
}

So, if two Strings are equals (s1.equals(s2) is true) then s1.intern() == s2.intern() is true.

alain.janinm
  • 19,951
  • 10
  • 65
  • 112