Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding a NullPointerException when the user enters invalid data

Tags:

java

How can I avoid a NullPointerException here if the user passes a null value for a date? Ideally, I would use a simple if statement.

SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm");
String layupDate = dateFormatter.format(orderLayupDateSet.getLayupDate());  
String layupTime = timeFormatter.format(orderLayupDateSet.getLayupDate());
if(layupDate == null) {
}
like image 483
TIM Avatar asked Nov 07 '22 06:11

TIM


1 Answers

You validate the date (orderLayupDateSet.getLayupDate()) in a liner (just creating a new date if null here but you can do as you please);

(orderLayupDateSet.getLayupDate() == null) ? new Date() : orderLayupDateSet.getLayupDate()

You can also go the traditional

if (orderLayupDateSet.getLayupDate() == null) {
   orderLayupDateSet.setLayupDate(new Date());
}

Or you can do it the other way around with a utility, and calling the utility function to check for you - seeing that you return a String in your example above. Like the below;

public class DateUtils {
    public static String formatDateTime(Date dateOrNull) {
        return (dateOrNull == null ? null : DateFormat.getDateTimeInstance().format(dateOrNull));
    }
}

Which in your code can be

String layupDate = (orderLayupDateSet == null || orderLayupDateSet.getLayupDate() ? null : dateFormatter.format(orderLayupDateSet.getLayupDate()));  
like image 126
Mez Avatar answered Nov 14 '22 23:11

Mez