-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
  • 91,013
  • 29
  • 181
  • 233

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
  • 464,258
  • 100
  • 912
  • 987
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
  • 14,745
  • 24
  • 85
  • 122
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,596
  • 3
  • 18
  • 15