-2

I've a simple code as below and it returns false when I have a space after "N/A" string.

String a = "N/A ";
if((a.trim())=="N/A")
{
 System.out.println("true");
}
else{
 System.out.println("false");
}

if I remove the space as "N/A" then it returns true. What am I missing here. I know I'm making a silly mistake couldn't figure it out.

Thanks in advance.

Jay Mayu
  • 16,523
  • 31
  • 112
  • 147

4 Answers4

5

First of all, don't compare strings using == operator. Use if(a.trim().equals("N/A")), it should help. Read for example here about comparing objects in Java.

Piotr Sobczyk
  • 6,215
  • 6
  • 46
  • 67
2

Try below...

String a = "N/A ";
if(a.trim().equals("N/A"))
{
 System.out.println("true");
}
else{
 System.out.println("false");
}

== compares object and .equals() compares values.

see this

Ketan
  • 5,011
  • 8
  • 34
  • 66
1

Have you tried using equals to compare instead of object identity?

Has QUIT--Anony-Mousse
  • 73,503
  • 12
  • 131
  • 189
1

Use equals() instead of == also fix the the paratheses issue in if condition

aviad
  • 7,775
  • 9
  • 44
  • 92