Java – String literals and string object hash codes

String literals and string object hash codes… here is a solution to the problem.

String literals and string object hash codes

I read that strings declared as literals are created in string constant pools
String s1 = "hello";
String s2 = "Hello"; -> This does not create a new object and references the s1 reference.

And strings declared with the new keyword are created on both heap memory and string constant pools
String s3 = new String("Hello"); -> This creates a new object in the heap.
But does it create a new constant in the string constant pool, or does it use a constant from s1?

I have the following code.
The hash code for all s1, s2, and s3 returns the 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 understand == object of comparison.
Are there two “Hellos” defined in the string constant pool, one from s1 and one from s3?

Related Problems and Solutions