0

I'm just wondering why using == to check equality of HttpStatus.BAD_REQUEST is not working:

HttpStatus httpStatusCode ...;
if (httpStatusCode == HttpStatus.BAD_REQUEST) {}

I got it working by using equals method:

if (httpStatusCode.equals(HttpStatus.BAD_REQUEST)) {}

But, HttpStatus.OK is working as in:

if (httpStatusCode == HttpStatus.OK) {}

I discovered it when I had this code:

if (httpStatusCode == HttpStatus.OK) {
...
} else if (httpStatusCode == HttpStatus.BAD_REQUEST ) {
...
} else {
...
}

Assumming httpStatusCode is HttpStatus.BAD_REQUEST, instead of going through else if block, it went to else block. But, when I changed == to .equals(), it worked.

I'm using Spring Web 4.3.6.RELEASE. Is there any explanation on this? Thank you

Julez
  • 1,010
  • 22
  • 44
  • 2
    It shouldnt make any difference since `HttpStatus` is an enum, there should only be one instance, so reference equality should be fine. – Magnus Aug 31 '17 at 07:46
  • I have said, it didn't work using == but .equals(). – Julez Sep 05 '17 at 05:23

1 Answers1

1

Use value() method:

httpStatusCode.value() == HttpStatus.OK.value()

If you will look inside the HttpStatus.java file, you can see it is an enum and it has a value method which return an int value of the HttpStatus, so you can use it to compare your Status codes. And .equals works as it checks the enums value as == checks reference.

Bishal Jaiswal
  • 1,684
  • 13
  • 15