How to check Null value for Date Object

40,283

If you want to be more robust in avoiding NullPointerException,

if (newProfile != null) {
    Object obj = newProfile.get(Constants.DETAILS_EXPIRY_DATE_1);
    if (obj == null) {
        this.cStmt.setDate(15, null);
    } else {
        java.sql.Date sqlDate = new java.sql.Date(((java.util.Date)obj).getTime());
                this.cStmt.setDate(15,sqlDate);

    }
}
Share:
40,283
AngelsandDemons
Author by

AngelsandDemons

Updated on September 14, 2020

Comments

  • AngelsandDemons
    AngelsandDemons over 3 years

    I am using JSF 2.0 and RichFaces 3.3. In my View user will pich a date from a calendar. Tag used is <rich:calendar>. This is mapped in backing bean with Date object. However this field is optional and hence when user does not select a date the backing bean getter for this particular entry returns null, which is right.

    My problem is that I have to store this date in DB. So before storing I am type casting it in this manner:

    if (newProfile.get(Constants.DETAILS_EXPIRY_DATE_1).equals(null)) {
        this.cStmt.setDate(15,null);
    } else {
        java.sql.Date sqlDate = new java.sql.Date(((java.util.Date)newProfile.get(Constants.DETAILS_EXPIRY_DATE_1)).getTime());
        this.cStmt.setDate(15,sqlDate);
    }
    

    However it is throwing a NullPointerException in the if condition. I want to insert null value in DB when user does not select a date. How can I do this?

  • Shahzeb
    Shahzeb over 12 years
    Not only this answer is incorrect but has also got an upvote -unreal.
  • AngelsandDemons
    AngelsandDemons over 12 years
    @Vanathi My problem seems to be solved...I assumed that along with String, Date object can also be checked as null using .equals method and that is why it failed intially...
  • Buhake Sindi
    Buhake Sindi over 12 years
    @Vanathi, your answer is correct but your explanation is wrong.
  • learner
    learner over 11 years
    It worked for me. plz some expert may explain why is this wrong?