I was trying to understand String#intern method. Now it has caused even more confusion.
package com;
public class Main {
public static void main(String[] args) {
String s1 = new String("GFG"); // Line-1
String s2 = s1.concat("GFG"); // Line-2
s2.intern(); // Line-3
String s4 = "GFGGFG"; // Line-4
// s2.intern(); // Line -5
System.out.println(s2 == s4);
}
}
The above code prints true. If I comment line 3 and uncomment line 5 it is printed false.
For line 3 the SCP is checked and the String is added to SCP.
But how did s2 equals to s4 in that case ?
s2 is still referencing to an object in heap which is pointing to SCP constant. Right ?
Can anyone please explain what is happening ? I've gone through different SO questions, but was not able to understand it still.
EDIT
I'm just trying to understand the intern method. I know the difference b/w ==
and equals
and the latter is preferred.