11:12 pm - Saturday May 27, 2017

String object in String pool String intern( )

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

                                 This method returns the canonical representation for the string object. Intern string have an entry in the global string pool. Initially the pool is empty and the and the strings are maintained privately by the class string. When the intern method is invoked, if the pool already contains a string then the string from the pool is returned. Otherwise String object is added to the pool and a reference to this String object is returned.

Example Program


    public class Index3 {

    public static void main(String[] args)

     {

       String s1="welcome to java world";

       String s2="Canonical Representation";

       String s3=s1.intern();

       String s4=s2.intern();

       System.out.println("Intern value of s3:"+s3);

       System.out.println("Intern value of s4:"+s4);

       if(s1==s2)

         {

           System.out.println("Both Strings (s1 & s2)are equal");

         }

       else

        {

          System.out.println("Both Strings(s1 & s2) are not equal");

        }

       if(s1==s3)

        {

          System.out.println("Both Strings (s1 & s3)are equal");

         }

        else

        {

         System.out.println("Both Strings(s1 & s2) are not equal");

        }

        if(s2==s4)

         {

          System.out.println("Both Strings (s2 & s4)are equal");

          }

         else

          {

          System.out.println("Both Strings(s2 & s4) are not equal");

           }

    }

  }

Output

        Intern value of s3:welcome to java world

        Intern value of s4:Canonical Representation

        Both Strings (s1 & s2) are not equal

        Both Strings (s1 & s3)are equal

        Both Strings (s2 & s4)are equal

Description:

                                   In this program String s1 and s2 has assigned a values. The string s1 and s2 values is copied to another strings s3 and s4 using intern( ) and the values are stored in an empty pool and then the values are checked to find whether they are equal or not. If the strings are not in the pool then they are added into a pool but if the values are already in the pool,then the object is stored and the string values are returned.

Filed in: Java Examples

Comments are closed.