-3

I am running this program. To check string pool concept. I refer this link and added two more lines with equals method from Object class in java. Why I am getting different output for objRef1==objRef2 vs objRef1.equals(objeRef2). In my opinion they should be same.

public class Abc2 {
    public static void main(String[] args) {
        String s1 = "Cat";
        String s2 = "Cat";
        String s3 = new String("Cat");

        System.out.println("s1 == s2 :"+(s1==s2));
        System.out.println("s1.equals(s2) :"+(s1.equals(s2)));
        System.out.println("s1 == s3 :"+(s3==s2));
        System.out.println("s1.equals(s3) :"+(s3.equals(s2)));
    }
}
krishna
  • 413
  • 2
  • 10
  • 25
  • 4
    `==` denotes reference equality (are they same point in memory); `equals` denotes "content equality" are the contents of the two objects the same (ie are the two objects the same type and does `Cat` equal `Cat` and not `Dog`) – MadProgrammer Aug 07 '18 at 04:19
  • @MadProgrammer that means equals method from Object class is overridden in String class. – krishna Aug 07 '18 at 04:26
  • Yes, you could inspect the source code to see – MadProgrammer Aug 07 '18 at 04:27
  • krishna, I think you are correct in detail - but generally @MadProgrammer is right: the semantics of equals() are "content equality" while those of == are "reference equality". Object.equals() itself may be implemented as "reference equality" because there was nothing else it could do... – moilejter Aug 07 '18 at 04:28
  • @MadProgrammer Yes, you are correct. I am so impatient. – krishna Aug 07 '18 at 04:30
  • Are you saying that `s1 == s2` gives a different result than `s1.equals(s2)`? – Henry Aug 07 '18 at 04:30
  • @Henry: Yes, it can, and often does. If they were always the same, there would be no point having both. (Not in this specific case, since `s1` and `s2` are the same object, but in case of `s2` and `s3`, they are different.) – Amadan Aug 07 '18 at 04:36
  • @Amadan `s1`and `s2` are set to the same constant string from the string pool. So they should always be the same object, right? – Henry Aug 07 '18 at 04:39
  • Yes. I did not know whether you were referring specifically to this `s1` and `s2`, or any `s1` and `s2`. These specific `s1` and `s2` are both `==` and `equals`, as the OP's code demonstrates. – Amadan Aug 07 '18 at 04:40

1 Answers1

0

String is a complex datatype so == find two different refetences. Strings equals() compares the content instead of the reference. So two "Cat"s has the same content but arent the same object. Its like you try to say C:\test.txt and C:\test2.txt where the same file because they have the same content.

BDevGW
  • 347
  • 3
  • 15