-2

I know what a NullPointerException is and why it is thrown what is unclear to me is why it is thrown in my example since "a" is set to a new instance of my class in which the constructor of the class assigns a value to appointmentDate.

 if(a==null){
        return false;
    }
    if(a.getAppointmentDate().before(Calendar.getInstance())){
        throw new InvalidCalendarException("date before now");
    }  

When executing this code a Nullpointer Exception is thrown in the second if-condition and I have no idea why since this point shouldn't be reached in cased a is null ( a is an instance of a class with a private java.util.Calendar attribute). In the constructor of said class the attribute is set according to input. Can someone please help me? I have been trying to get a solution for several hours now :(

Lorin P.
  • 31
  • 1
  • 7
  • 1
    Well I *suspect* that `a.getAppointmentDate()` is returning null. But we can't check with only the code you've given. – Jon Skeet Jun 04 '16 at 18:50
  • As suggested above, your currently checking if the object `a` is null. However, you're not checking if the object's method is null. Assuming the method `getAppointmentDate()` returns a value, it is possible that this method is returning a null value. – Baleroc Jun 04 '16 at 18:52
  • This is bad coding, you should use variable names for each object, not just concatenate method calls: Date d = a.getAppointmentDate(); if (d.before(... This way you will see exactly where the exception happens. – sigma Jun 04 '16 at 18:59
  • @JonSkeet 1 min? you have an auto-close-script that triggers on NPE? :) – sigma Jun 04 '16 at 19:01
  • @sigma: I voted to close as "off topic because it didn't include a [mcve]" rather than as a duplicate, in this case... the OP appears to know what an NPE is, but hasn't provided a repro. – Jon Skeet Jun 04 '16 at 19:15

1 Answers1

0

Because a.getAppointmentDate() is returning null.

Try using the check

if(a==null || a.getAppointmentDate() == null)

Arpan
  • 355
  • 2
  • 10
blur0224
  • 972
  • 8
  • 26