0

I have some code which is effectively the following:

String a;
String b;
a = get_string_from_complex_procedure_1();
b = get_string_from_complex_procedure_2();
if (a != b)
{
    put_up_error_dialog("["+a+"] != ["+b+"]");
}

The code is designed such that a and b should end up identical, and indeed most of the time they are, but occasionally I get the error dialog appearing. The confusing thing though, is that the two strings appear identical to me when reported by the dialog. I'm wondering what sort of things can cause this problem?

Baz
  • 36,440
  • 11
  • 68
  • 94
Mick
  • 8,284
  • 22
  • 81
  • 173
  • 7
    Duplicate of *lots* of posts comparing strings using `==` or `!=`. Those only compare *references*. Use `equals` instead. – Jon Skeet Sep 07 '12 at 09:50
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – MByD Sep 07 '12 at 09:52
  • Sorry for the duplicate. I guess you will always get lots of duplicates for this question because it is not obvious what to search for. I was suspecting all sorts of subtle things like unicode vs ASCII characters or some such. – Mick Sep 07 '12 at 10:12

4 Answers4

5

Rewrite like this:

String a;
String b;
a = get_string_from_complex_procedure_1();
b = get_string_from_complex_procedure_2();
if (!a.equals(b))
{
    put_up_error_dialog("["+a+"] != ["+b+"]");
}

The == and != operators compare references, not values.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
1

You cannot use == and != on Strings. To compare two Strings use a.equals(b) and !a.equals(b)

Baz
  • 36,440
  • 11
  • 68
  • 94
slezadav
  • 6,104
  • 7
  • 40
  • 61
0

Use of == or != in case of String compares reference (memory location) so better you use equals() method.

Baz
  • 36,440
  • 11
  • 68
  • 94
kanhai shah
  • 1,193
  • 10
  • 14
0

use

       a.equals(b); or  a.equalsIgnoreCase(b) to compare String. 
Rajendra
  • 1,700
  • 14
  • 17