How would I go about fixing a NullPointerException of the following code?
Solution 1
Since you've indicated that the NullPointerException
is thrown on line 2, we can deduce that you're passing in null
for the currentDate
argument. currentDate.getTime()
is the only part of line 2 that can cause a NullPointerException
.
Update:
I just wrote the following Test.java
code to really understand what your problem is:
import java.util.*;
import java.text.*;
class Test {
public static void main(String[] args) {
Date thisDate = null;
try {
thisDate = (new SimpleDateFormat("MM/dd/yyyy")).parse(Calendar.getInstance().getTime().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
When I run it, I get:
java.text.ParseException: Unparseable date: "Sat Aug 20 12:42:30 PDT 2011"
at java.text.DateFormat.parse(DateFormat.java:337)
at Test.main(Test.java:8)
So the problem is that your SimpleDateFormat.parse()
expects the month/day/year format, but the Date
class's toString()
method is giving you something different.
It seems as though all you really want is the current date. Why bother formatting it? Just trim it down to this and be done with it:
Date thisDate = new Date(); // this gives you the current date
Solution 2
What your line:
thisDate = (new SimpleDateFormat("MM/dd/yyyy")).parse(Calendar.getInstance().getTime().toString());
does is
- create a new Calender object (initialised with the curren time),
- get a Date() object from it,
- convert that to string which will use a default format like "EEE MMM d HH:mm:ss z yyyy"
- and try to parse the result as a date with the format "MM/dd/yyyy"
- (which will fail to parse by design, resulting in a
null
)
If you fix all problems in this line, the end result will be a Date
object containing the current time.
A much easier way to obtain such a Date
is:
thisDate = new Date();
Related videos on Youtube
Dylan Wheeler
I grew up in the small town of Bow, NH, and graduated summa cum laude from the University of New Hampshire with bachelor's degrees in information technology and philosophy. I'm an entrepreneur at heart and founded two EdTech startups. ecoText's mission is to become the ultimate collaborative learning tool while delivering affordable digital textbooks to students. I helped the company raise over $650,000 in funding. In high school, I founded Triumph Software to launch a professional development management tool, Loggit. The app has since served over 500 educators across New Hampshire and tracked more than 100,000 professional development hours. When I'm not tackling challenging problems, I enjoy writing, photography, and building deep interpersonal relationships while pondering my place in the universe.
Updated on June 04, 2022Comments
-
Dylan Wheeler almost 2 years
I have this code and when I run the script, I pass in valid parameters, but I keep on getting a NPE. Help?
Code:
private static Date getNearestDate(List<Date> dates, Date currentDate) { long minDiff = -1, currentTime = currentDate.getTime(); Date minDate = null; if (!dates.isEmpty() && currentDate != null) { for (Date date : dates) { long diff = Math.abs(currentTime - date.getTime()); if ((minDiff == -1) || (diff < minDiff)) { minDiff = diff; minDate = date; } } } return minDate; }
I get the NullPointerException from line 2 of the code above and I use the following code to pass in thisDate as the currentDate variable.
Date thisDate = null; try { thisDate = (new SimpleDateFormat("MM/dd/yyyy")).parse(Calendar.getInstance().getTime().toString()); } catch (Exception e) {}
-
Jon Skeet over 12 yearsWhere are you getting the NPE, and what do the arguments look like? A short but complete program would help...
-
Dylan Wheeler over 12 yearsDoes my edit help with your concerns?
-
tichy over 12 yearsHm, my shot is you have nulls as list elements. dates might not be null but may have elements of null. Assuming dates is really valid and not null.
-
Bhaskar over 12 yearsmay be you can post the exception stack trace ? Atleast the main lines telling exactly where the exception is being thrown .. that would definitely help, my guess is that currentDate is being passed in as null..
-
Nannewell, what line gives you the npe...
-
JornIf it's line 2, it has to be the
currentDate
argument that'snull
.
-
-
Asaph over 12 yearsYour description of what's happening in the code is wrong. Specifically this part: "get its number of milliseconds attribute". That never happens. What happens is this:
Calendar.getInstance().getTime()
returns ajava.util.Date
and then you're just callingtoString()
on that. You never get number of milliseconds. -
rsp over 12 years@Asaph, good catch! Updated to reflect what actual happens :-)
-
Asaph over 12 yearsNow this part is wrong:
convert that to string which will use the default format "yyyy-mm-dd"
. An example of a formatted date string returned byjava.util.Date.toString()
is this:Sat Aug 20 12:42:30 PDT 2011
.