I read that strings declared as literals are created on String Constant Pool
String s1 = "Hello";
String s2 = "Hello";
-> This will not create a new object and will refer to the s1 reference.
And strings declared with new keyword are created on both Heap Memory and String Constant Pool
String s3 = new String("Hello");
-> This will create a new object in the heap.
But will it create a new constant in the String Constant Pool also or will it use the one from s1?
I have this following code. Hashcode for all s1, s2, and s3 are return as same.
public class question1 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1 == s3); // not sure why false result, s3 will create a separate constant in the pool? There is already a constant with value "Hello" created by s1. Please confirm if s3 will again create a constant.
}
}
I understant that ==
compares the object.
Are there two "Hello" defined in the String Constant Pool, one from s1 and one from s3?