Home » Android » java – String.equals() always return true

java – String.equals() always return true

Posted by: admin June 15, 2020 Leave a comment

Questions:

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);
}
How to&Answers:

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.

Answer:

Remove the ; after the if statement.

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

Answer:

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

Answer:

if(CompleteString.equals(resultString));

It won’t enter in if block it looks like a empty condition 🙂

Answer:

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);
}

Answer:

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);
}