-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
  • 17,023
  • 32
  • 114
  • 148

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,443
  • 7
  • 47
  • 70
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 Bhavsar
  • 5,338
  • 9
  • 38
  • 69
1

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

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
1

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

aviad
  • 8,229
  • 9
  • 50
  • 98