Inconsistent Date Parsing with SimpleDateFormat in Java 8 - Unexpected NullPointerException
I'm trying to configure I'm working with a `NullPointerException` when trying to parse date strings using `SimpleDateFormat` in Java 8..... The scenario arises when I attempt to parse dates that are formatted inconsistently. For example, I have a method that is supposed to parse various date formats, and it fails on some inputs, specifically when the input string is `null` or empty. Here's my code snippet: ```java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class DateParser { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); public static Date parseDate(String dateString) throws ParseException { if (dateString == null || dateString.isEmpty()) { throw new IllegalArgumentException("Date string want to be null or empty"); } return dateFormat.parse(dateString); } } ``` When I call this method with a `null` value: ```java public static void main(String[] args) { try { Date date = DateParser.parseDate(null); } catch (Exception e) { System.out.println(e.getMessage()); } } ``` I expect to see "Date string want to be null or empty", but instead, I get a `NullPointerException` at the line where `dateFormat.parse(dateString)` is called. I've ensured that the check for `null` is done before parsing, so I'm puzzled as to why this is happening. I've also tried using `Optional` to handle potential `null` values, but it seems unnecessary since I should be catching it before reaching the `parse` method. I want to ensure that this method is robust and doesn't throw unhandled exceptions. Can anyone guide to understand why this is occurring and how to avoid it? I'm developing on Ubuntu 20.04 with Java. Am I missing something obvious? What are your experiences with this?