0

I have the following code snippet

  format(Object obj) {
    if(obj.equals("false")) {
      buffer.append("No");
    } else {
      buffer.append("Yes");
    }
  }

When debugging, I verify that the value of obj variable is a Boolean object with the value "false", but the if clause always go to the Yes instruction. Can you help me understand why?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
tt0686
  • 1,771
  • 6
  • 31
  • 60
  • 4
    Are you expecting something like `Boolean.valueOf(false).equals("false")` to return true? You're comparing a `Boolean` to a `String`... Maybe you want `obj.toString().equals("false")` (or `equalsIgnoreCase`). – ernest_k Jul 21 '21 at 14:24
  • 3
    You're trying to compare `String` with `Boolean`. that's why you're getting `fasle` – dehasi Jul 21 '21 at 14:24
  • Does this answer your question? [How to compare Boolean?](https://stackoverflow.com/questions/22491853/how-to-compare-boolean) – Nexevis Jul 21 '21 at 14:27

1 Answers1

2

When you run obj.equals("false") you're trying to compare obj, a Boolean, with "false", which is a String.

So you can try to first convert the Boolean to a string:

if(obj.toString().equals("false")){
    buffer.append("No");
} else {
    buffer.append("Yes");
}

Or, even better, as suggested by @Nexevis, you can compare obj directly to a Boolean:

if(obj.equals(false)){
    buffer.append("No");
} else {
    buffer.append("Yes");
}
Crih.exe
  • 502
  • 4
  • 16