Java – String intern() Example, Strings intern() program

String objects and string characters can be compared with the help of intern() method in java. intern() method returns value in String. Two different instance of string objects can be matched with intern() and == operator. If string objects are matched with each other in string, it will return true, otherwise false. Use of String intern() in java is shown below.

intern() method is much faster than equals() of java. equals() method compare strings with character by character. intern() helps to compare by objects.

Example of String intern() in java, JSP

public class StringInternExample {

    public static void main(String[] args) {

        String string1 = new String("find strings");

        String string2 = "new strings";

        String string3 = new String("find strings");

        // intern is faster it check point to point object
        if(string1.intern()==string2.intern())
            System.out.println("String 1 & 2 matched");
        else
            System.out.println("String 1 & 2 not matched");

        if(string1.intern()==string3.intern())
            System.out.println("String 1 & 3 matched");
        else
            System.out.println("String 1 & 3 not matched");

        if(string1==string3)
            System.out.println("String == 1 & 3 matched");
        else
            System.out.println("String == 1 & 3 not matched");

        // equals method is slower it compares character by character
        if(string1.equals(string3))
            System.out.println("String 1 & 3 equals matched");
        else
            System.out.println("String 1 & 3 equals not matched");

    }
}

Output

String 1 & 2 not matched
String 1 & 3 matched
String == 1 & 3 not matched
String 1 & 3 equals matched

Tags:

Bookmark  

 

Leave a Reply

Security Code:

 

  Random Post