-1

I am learning Java now. When I use == and .equals() for String comparisons, I am getting different results. But there is no compilation error. Can anyone explain the difference between these two operations?

Maroun
  • 94,125
  • 30
  • 188
  • 241

3 Answers3

2
  • s1 == s2 compares string references; this is very rarely what you want.
  • s1.equals(s2) compares the two character sequences; this is almost always what you want.
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

== tests for reference equality.

.equals() tests for value equality.

Example:

String fooString1 = new String("Java");
String fooString2 = new String("Java");

// false
fooString1 == fooString2;

// true
fooString1.equals(fooString2);

Note:

== handles null strings values.

.equals() from a null string will cause Null Pointer Exception

Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
0

when == is used for comparision between String then it checks the reference of the objects. But when equals is used it actually checks the contents of the String. So for example

  String a = new String("ab");
  String b = new String("ab");
  if(a==b) ///will return false because both objects are stored on the different locations in memory

   if(a.equals(b)) // will return true because it will check the contents of the String

i hope this helps

user_CC
  • 4,686
  • 3
  • 20
  • 15