Memento
Memento

Reputation: 785

String.equals() always return true

K want to compare two strings but the equals() method always return true , so the if statement always runs. why this happens?

resultString = "Test1";
String CompleteString = "Test";
if(CompleteString.equals(resultString));
{
   rowView.setBackgroundResource(R.color.listselect_red);
}

Upvotes: 8

Views: 5387

Answers (6)

Jeevan Roy dsouza
Jeevan Roy dsouza

Reputation: 673

It is because of semicolon in if condition..

Correct code

resultString = "Test1";
String CompleteString = "Test";
if(CompleteString.equals(resultString))
{
   rowView.setBackgroundResource(R.color.listselect_red);
}

Upvotes: 2

SpringLearner
SpringLearner

Reputation: 13844

remove ; from if(CompleteString.equals(resultString));

; means end of statement so even the if() loop returns false or true all the statements present after if() will be executed.So rowView.setBackgroundResource(R.color.listselect_red); will be executed all the time.

try this way

resultString = "Test1";
String CompleteString = "Test";
if(CompleteString.equals(resultString))// removed `;`
{
   rowView.setBackgroundResource(R.color.listselect_red);
}

Upvotes: 2

No_Rulz
No_Rulz

Reputation: 2719

if(CompleteString.equals(resultString));

It won't enter in if block it looks like a empty condition :)

Upvotes: 2

sofia
sofia

Reputation: 91

it is because of the ';' at the end of if . Just remove and it will work !

Upvotes: 2

Chronicle
Chronicle

Reputation: 1645

Remove the ; after the if statement.

if(CompleteString.equals(resultString))
{
  rowView.setBackgroundResource(R.color.listselect_red);
}

Upvotes: 4

Alexis C.
Alexis C.

Reputation: 93842

if(CompleteString.equals(resultString)); <-- remove the ;

Your code is the equivalent to :

if(CompleteString.equals(resultString))
{
  //empty block
}
{
   rowView.setBackgroundResource(R.color.listselect_red);
}

So if equals returns true, the empty block will be executed, and after the second block will be always executed whatever the if was false or true.

Upvotes: 20

Related Questions