I need your help in initializing a java.util.Date
variable to empty. As I am running the page and it is showing NullPointerException
if I didn't select any date.
The code is:
private java.util.Date date2;
I tried to make that variable empty, but it didn't work
private java.util.Date date2;
if (date2 == null || date2.equals(""))
date2 = "";
However, with the initialization:
private java.util.Date date2 = new java.util.Date(0,0,0);
The above code will give me a default value which I don't want it.
This question is related to
java
It's not clear how you want your Date logic to behave? Usually a good way to deal with default behaviour is the Null Object pattern.
IMO, you cannot create an empty Date(java.util)
. You can create a Date
object with null
value and can put a null check.
Date date = new Date(); // Today's date and current time
Date date2 = new Date(0); // Default date and time
Date date3 = null; //Date object with null as value.
if(null != date3) {
// do your work.
}
Try initializing with null value.
private java.util.Date date2 = null;
Also private java.util.Date date2 = "";
will not work as "" is a string.
An instance of Date always represents a date and cannot be empty. You can use a null value of date2 to represent "there is no date". You will have to check for null whenever you use date2 to avoid a NullPointerException, like when rendering your page:
if (date2 != null)
// print date2
else
// print nothing, or a default value
Source: Stackoverflow.com