-4
Boolean valid = null;
if (valid == null) {
    log.info("******");
}

I have the expression above, I wanted to check if Boolean value is null and if it is then execute statement inside if clause, but what happened is that it throws me a NullPointerException. What should I do to have my if clause evaluated with that given condition valid == null. Thanks in advance

Neuron
  • 5,141
  • 5
  • 38
  • 59
Zerosero
  • 323
  • 3
  • 15
  • 2
    The first thing you should do is ask yourself why you would ever use a `Boolean` object and assign it null. Other than that your code works. Probably `log` is a null-reference you can't call a method on. – Ben May 28 '18 at 06:16
  • 5
    This code doesn't throw NullPointerException (unless `log` is `null`) – Eran May 28 '18 at 06:17
  • Probably your "log" object that is not instantiated. – B. Bri May 28 '18 at 06:17
  • As it is, it won't throw a nullpointerexception. That would happen though if you unboxed the boolean, or if you tried `if(valid)` – ernest_k May 28 '18 at 06:18
  • thanks everyone. I forgot that before the expression "valid == null" I checked it first if its "!valid", hence I got NPE since first expression evaluates if it contains a value which is false. – Zerosero May 29 '18 at 00:24

1 Answers1

0

For sure, your log object contains null reference. You can't invoke any method with null reference. Try this:

Boolean valid = null;
if(valid == null) {
     System.out.println("Hello");
}
Abhishek
  • 688
  • 6
  • 21