Reputation: 7947
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
Reputation: 1333
Use of ==
or !=
in case of String compares reference (memory location) so better you use equals()
method.
Upvotes: 0
Reputation: 6141
You cannot use ==
and !=
on Strings. To compare two Strings use a.equals(b) and !a.equals(b)
Upvotes: 1
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