-4

Why two string objects which are declared using String class constructor with identical string literal are not equal when compared using equality operator '==', but when declared directly by assigning identical string literals are equal.

String s1 = new String("hello");
String s2 = new String("hello");
Boolean result1 = (s1 == s2);// returns false

String s3 = "hello";
String s4 = "hello";
Boolean result2 = (s3 == s4);// returns true
Leo The Four
  • 699
  • 9
  • 14

1 Answers1

0

enter image description heres1 and s2 are 2 different objects and so the references are not equal

During s3,object is created in String pool and during s4 no new object is created as hello is already present.So s4 only points to hello object present pool.

As now both s3 and s4 points to the same object and so the references are same.

As you know == checks for the references so it return true

SpringLearner
  • 13,738
  • 20
  • 78
  • 116