0

I have the following code:

String s1= "Hi";
String s2="Hi";
String s3=s1.concat(" a");
String s4="Hi a";
System.out.println(s1==s2);
System.out.println(s1=="Hi");
System.out.println(s3.equals(s4));
System.out.println(s3==s4);

Why is System.out.println(s3==s4) false?

shapiro yaacov
  • 2,308
  • 2
  • 26
  • 39
Archana Mundaye
  • 523
  • 1
  • 5
  • 19

1 Answers1

2

This is the difference between == and .equals().

== checks that the references for the two objects are equal

.equals() is implemented by the object to check whether it is equal with another object

== should only be used for primitive types

jiaweizhang
  • 809
  • 1
  • 11
  • 28
  • I know that == is for reference and equals should be used for value compare but what this String s3=s1.concat(" a"); line doing, specialy concat word because of which System.out.println(s3==s4); is returning false. – Archana Mundaye Nov 19 '15 at 08:59
  • Since java.lang.String class override equals method, It return true if two String object contains same content but == will only return true if two references are pointing to same object – Mukesh Kumar Nov 19 '15 at 09:30