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.
解决方案
Instance of java.util.Date stores a date. So how can you store nothing in it or have it empty? It can only store references to instances of java.util.Date. If you make it null means that it is not referring any instance of java.util.Date.
You have tried date2=""; what you mean to do by this statement you want to reference the instance of String to a variable that is suppose to store java.util.Date. This is not possible as Java is Strongly Typed Language.
Edit
After seeing the comment posted to the answer of LastFreeNickname
I am having a form that the date textbox should be by default blank in the textbox, however while submitting the data if the user didn't enter anything, it should accept it
I would suggest you could check if the textbox is empty. And if it is empty, then you could store default date in your variable or current date or may be assign it null as shown below:
if(textBox.getText() == null || textBox.getText().equals(""){
date2 = null; // For Null;
// date2 = new Date(); For Current Date
// date2 = new Date(0); For Default Date
}
Also I can assume since you are asking user to enter a date in a TextBox, you are using a DateFormat to parse the text that is entered in the TextBox. If this is the case you could simply call the dateFormat.parse() which throws a ParseException if the format in which the date was written is incorrect or is empty string. Here in the catch block you could put the above statements as show below:
try{
date2 = dateFormat.parse(textBox.getText());
}catch(ParseException e){
date2 = null; // For Null;
// date2 = new Date(); For Current Date
// date2 = new Date(0); For Default Date
}