Java String intern()

String class in java has a native method intern(), so there is no implementation details in the class code but as the description says, it returns the String with same value and it’s from String Pool.

The java.lang.String.intern() method returns a canonical representation for the string object.A pool of strings, initially empty, is maintained privately by the class String.

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.

Declaration

Following is the declaration for java.lang.String.intern() method

public String intern()
Parameters

NA

Return Value

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

Exception

NA

Java String intern() method example
public class Test1 { public static void main(String args[]) { String s1 = new String("abc"); //goes to Heap Memory, like other objects String s2 = "abc"; // goes to String Pool String s3 = "abc"; //again, goes to String Pool //Let's check out above theories by checking references System.out.println("s1==s2? "+(s1==s2)); //should be false System.out.println("s2==s3? "+(s2==s3)); //should be true //Let's call intern() method on s1 now s1 = s1.intern(); // this should return the String with same value, //BUT from String Pool //Let's run the test again System.out.println("s1==s2? "+(s1==s2)); //should be true now } }


Output:
s1==s2? false s2==s3? true s1==s2? true
Example

The following example shows the usage of java.lang.String.intern() method.

mport java.lang.*; public class Test1 { public static void main(String[] args) { String str1 = "This is cprogramcoding"; // returns canonical representation for the string object String str2 = str1.intern(); // prints the string str2 System.out.println(str2); // check if str1 and str2 are equal or not System.out.println("Is str1 equal to str2 ? = " + (str1 == str2)); } }


Output:
This is cprogramcoding Is str1 equal to str2 ? = true
Java String intern() method example
public class Test1 { public static void main(String args[]) { String s1=new String("hi"); String s2="hi"; String s3=s1.intern(); //returns string from pool, //now it will be same as s2 System.out.println(s1==s2); //false because reference variables are //pointing to different instance System.out.println(s2==s3); //true because reference variables //are pointing to same instance } }


Output:
false true



Instagram