Jannis Alexakis
Jannis Alexakis

Reputation: 1319

nullPointerException on a nullable=false value

This method does the following : it gets the int startAge from the Database. This parameter has a set default of 0 and is not nullable. Then it checks if it´s bigger than zero, in which case it adds it to dob and returns it.

Pretty simple, actually, but i keep getting a NullPointerException on the marked line, although the Database makes sure the variable CANNOT be null and the parameter groupFrom in the entity class is also set to nullable=false.

Any hints ?

public static DateMidnight getRealStartDate(DateMidnight startDate, DateMidnight dob, Groups group){
    DateMidnight realStart = null;
    int startAge = group.getGroupFrom(); //nullPointerException
    if (startAge > 0) {
        realStart = dob.plusMonths(startAge);
    } else {
        realStart = startDate;
    }   
    return realStart;
}

Upvotes: 0

Views: 188

Answers (5)

Udo Held
Udo Held

Reputation: 12538

Even though it's ugly. If you cannot use a debugger:

Insert these lines on your second line:

if (group == null) {
  System.out.println("group is null");
} else {
  System.out.println("group isn't null");
}

I'm sure it will print "group is null", because something with your assumptions is not working.

You could use tools like log4j or slf4j for doing a more professional output. :)

Upvotes: 1

EdgeCase
EdgeCase

Reputation: 4827

To state what the others have said slightly differently, you might be confusing the value of the field in the database which is probably not NULL, with the value of the object group in the call below. The getGroupFrom Method could also have a bug in it that is preventing it from returning the correct value from the database.

group.getGroupFrom()

Upvotes: 1

hovanessyan
hovanessyan

Reputation: 31443

Better use assertions where your not completely sure in your code. In the group example

 DateMidnight realStart = null;
 assert group != null;
 int startAge = group.getGroupFrom(); //nullPointerException

Upvotes: 1

Gray
Gray

Reputation: 116878

I suspect that there is data in the database that has group == null. Although group is set with nullable=false this is only an INSERT restriction as far as I know. There is probably rows already in the database with a null group. Maybe another entity is inserting data that does not have the nullable restriction?

Can you do a query of the database looking for null groups to see if they exist?

SELECT COUNT(*) FROM foo WHERE 'group' IS NULL;

Hope this helps.

Upvotes: 1

Tesseract
Tesseract

Reputation: 8139

If you get a NullPointerException at that line it means that the variable group is null.

Upvotes: 0

Related Questions