Mick
Mick

Reputation: 7947

Strings look the same but test says they are different

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?

Upvotes: 0

Views: 351

Answers (4)

Rajendra
Rajendra

Reputation: 1698

use

       a.equals(b); or  a.equalsIgnoreCase(b) to compare String. 

Upvotes: 0

kanhai shah
kanhai shah

Reputation: 1333

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

Upvotes: 0

slezadav
slezadav

Reputation: 6141

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

Upvotes: 1

Bart Friederichs
Bart Friederichs

Reputation: 33533

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.

Upvotes: 5

Related Questions