3

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?

Sun Shine
  • 575
  • 2
  • 6
  • 20
  • 4
    `hashCode` has nothing to do with references being the same. `hashCode` only cares about `.equals`, not `==`. `s3` is not in the constant pool at all. – Louis Wasserman Jul 11 '17 at 18:27
  • 4
    `==` tests whether two objects are exactly the same object. `new` *always* creates a new, separate object. – VGR Jul 11 '17 at 18:27
  • imagine hashcode as your day of birth, you and your neighbour may have the same day of birth, but you are not the same person! – ΦXocę 웃 Пepeúpa ツ Jul 11 '17 at 18:37
  • s3 will use the same constant created by s1 or it will create a separate constant in the pool and also the object? – Sun Shine Jul 11 '17 at 21:34

1 Answers1

3

String literals are automatically "interned," which places them in a pool. This minimizes the number of instances required. So, the two literals use the same String instance. hashCode() operates on the contents of the String in a consistent way. If two String instances have the same characters, then they will have the same hash code.

Steve11235
  • 2,849
  • 1
  • 17
  • 18
  • It means, then we have two constants in the constant pool? s1 created one constant and s3 created a object in the heap then s3 also created a constant? Or it is going to use the constant create by s1? – Sun Shine Jul 11 '17 at 21:31
  • string literal is automatically interned while the "new String()" causes string object to be created in heap but doesn't create similar string in String Constant Pool. To create similar string in String Constant Pool, call inter() on that new string object. – Daniyal Javaid Mar 14 '20 at 18:49
  • neither s3 creates constant in pool nor it reuses the constant already placed in pool – Daniyal Javaid Mar 14 '20 at 18:50