0

Why when I try to do the following: (in java)

if (reason.equals("time")) { // my code }

The IDE shows me this warning message: (?)

Method invocation 'reason.equals("time")' may produce 'java.lang.NullPointerException'

I couldn't find an abstract explanation to this warning message.

Ofer Arial
  • 1,129
  • 1
  • 10
  • 25
  • 1
    It's telling you that at this point in the code, `reason` might be `null`; and if it is, your program will throw an exception. – khelwood Feb 01 '17 at 15:39
  • If you know what a `NullPointerException` is that warning shouldn't be that hard to understand. Thus I assume you'll want to read [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Thomas Feb 01 '17 at 15:43

2 Answers2

6

If reason is null, you'll basically have null.equals("time") which causes a NullPointerException. To fix this, simply swap the two: "time".equals(reason);

QBrute
  • 4,405
  • 6
  • 34
  • 40
5

It's your IDE being cute. If reason is null then you could well get a java.lang.NullPointerException.

A common workaround is to use java.util.Objects.equals(reason, "time"). That function will perform any null checks for you.

Although, for this particular case, the cool cats, knowing that the literal is certainly not null, will rewrite to the Yoda Expression

"time".equals(reason)

Reference: https://en.wikipedia.org/wiki/Yoda_conditions

Bathsheba
  • 231,907
  • 34
  • 361
  • 483