Why intern method doesn't return equal string in java

public static void main (String[] args) { String s1 = new String("hello"); String s2 = new String("hello"); s1.intern(); s2.intern(); System.out.println(s1 == s2); // why this returns false ? } 

according to my understanding, the 1st call to the intern method was to create a "pool-pool-pool" with one line of "hello" . the second call to the intern method would not do anything (since the string "hello" already in the pool). Now when I say s1 == s2 , I expect the JVM to compare the string "hello" with the static string pool and return true .

+5
source share
4 answers

The intern() method does not change the string, it simply returns the corresponding string from the string pool. So, since you are not saving the return values, your calls to intern() pointless. However, if you really use them, you will see that both point to the same line:

 public static void main (String[] args) { String s1 = new String("hello"); String s2 = new String("hello"); s1 = s1.intern(); s2 = s2.intern(); System.out.println(s1 == s2); // will print true } 
+4
source

You simply check the source lines that reference different objects in the heap. You do not store the return value of the String # intern () method .

It should be

 String s1 = new String("hello"); String s2 = new String("hello"); String s11 = s1.intern(); String s22 = s2.intern(); System.out.println(s11 == s22); // returns true 
+4
source

String.intern returns a new interned string. To change s1 and s2 you do

 s1 = s1.intern(); s2 = s2.intern(); 

s1 == s2 will return true.

+3
source

The string property that you need to assign after calling this method, let's take an example, even if:

 String S1= "Hello"; S1.concat("World"); 

and if you print the value of S1, it will print only "Hello". but if you write like this:

 S1=S1.concat(" World"); 

then he will print "Hello World".

Similarly, you need to assign a value as:

 s1=s1.intern(); s2=s2.intern(); 

and if you compare s1 == s2, it will return the true value, but, say:

 String s3=s1.intern(); String s4=s2.intern(); 

and if you compare s3 == s4, then its true, but (s3 == s1) and (s4 == s2) will be false.

+1
source

Source: https://habr.com/ru/post/1200477/


All Articles