-4

I have 2 Strings with name str1 that fills by data from url and str2 that fills by data from SQLite Database.str1 is "x4" and str2 is "x4" but when i want to compare them,they are not equals.

if(str1.equals(str2)) System.out.println(str1 + "=" + str2);
else System.out.println(str1 + "!=" + str2);

and always it prints x4!=x4.

I changed values but always is not equals.

3 Answers3

2

Database.str1 is "x4" and str2 is "x4"

It might look like that, but I bet that's not the case. Why not print out the char array for each string, and that way you can identify what differs? I would suggest looking for leading/trailing spaces, non-printing characters, Unicode-related differences etc.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

Try changing it to:

StringBuilder string = new StringBuilder();
string.append("'");
string.append(str1);
string.append("'");

if(!str1.equals(str2)){
    string.append("!");
}

string.append("'");
string.append(str2);
string.append("'");
System.out.println(string.toString());

It is most likely that there is a space, enter or a tab in one of the strings. By adding a character at the start and end of each string then you can identify if that is the case.

If the problem persists then that probably means that one of the characters that is different is not printable. In that case try:

string.append(str1.toCharArray()); 

instead of

string.append(str1);

And do the same for str2.

nick zoum
  • 7,216
  • 7
  • 36
  • 80
0

It could have been caused either due to trailing spaces, as a_horse_with_no_name said, or (maybe you didn't notice) due to case difference. Try this:

if(str1.trim().equalsIgnoreCase(str2.trim()))
    System.out.print(str1 + "=" + str2);
else
    System.out.print(str1 + "!=" + str2);

Use trim() to remove trailing spaces and use equalsIgnoreCase() instead of equals(), considering case difference.

Community
  • 1
  • 1
progyammer
  • 1,498
  • 3
  • 17
  • 29