I know that String is immutable. In the example below a String constant object will be created in String pooled area and s1 will point to the "Hello". Also s2 will make a String constant with the same value "Hello".
But I don't understand why s2 do not point to the first "Hello". From what I understand String "Hello" already exist in the String pooled area and if I create another String with this value, it will point to the existing object rather than create another object. For example s3 points to the same object like s1.
I didn't use new keyword for s2. Why s2 doesn't point to the same object like s1 and s3?
public class DemoApp {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello friends".substring(0, 5);
String s3 = "Hello";
System.out.println(s2); //Hello
System.out.println(s1 == s2); //false
System.out.println(s1 == s3); //true
}
}
The output is:
Hello
false
true