Search code examples
javanull-check

Is null check required here?


I come across this line of code in my project:

String statusRecoTime = sdf.format(cal.getTime());

Then there is a null check like

if (statusRecoTime != null) {
     //do something
}

I think that the statusRecoTime will never be null and there is no need of this check because it is assigned with an object.

Please let me know if my understanding is correct?


Solution

  • Assuming that sdf is a SimpleDateFormat instance, format will never return null. The null check is completely unnecessary.

    Various answers here concern themselves with whether that code will throw an exception. The only time it would is if sdf or cal were null. But assuming both are non-null and cal is a Calendar, that code won't throw an exception.