My method takes a Date object. And I am passing a null value.How can I check if the (Date date) date is null or not.I am new in Stackoverflow, If the question is not a good one please don't undergrade the post.
Asked
Active
Viewed 1.2e+01k times
8
-
the == operator comes to mind. – Stultuske Jan 22 '16 at 10:17
-
1how about a a simple if check? if(date == null) – Michael Faisst Jan 22 '16 at 10:18
-
thanks a lot buddies. – maman Jan 22 '16 at 10:19
-
@AndreasFester That other Question is more about the Bitwise OR operator than it is about testing for Null. – Basil Bourque Jan 22 '16 at 20:08
-
1@BasilBourque Thats true - it should nevertheless give some hint on how to do a null check in general. A better answer is probably at http://stackoverflow.com/questions/21664478/java-object-null-check-for-method. But there are now also many specific answers to OP's concrete question below ;-) – Andreas Fester Jan 22 '16 at 20:24
4 Answers
17
Check if it is null:
if (date == null) {...}
Check if it is not null:
if (date != null) {...}

James
- 1,471
- 3
- 23
- 52
-
3Tip: Putting the null on the left side helps to avoid accidentally using a single `=` thereby making an assignment rather than a test. Like this: `if ( null == date )` and `if( null != date )`. Also, the null on the left may be easier to read as your brain instantly knows you are doing a null test of something. – Basil Bourque Jan 22 '16 at 20:11
2
In Java 8 you could use an Optional<Date>
and check its empty()
or isPresent()
methods.

Aaron
- 24,009
- 2
- 33
- 57
-1
Java Code : Check if date is null
public static void main( String[] args )
{
Date date = showDate();
//check with if-else statement with equals()
if ( !date.equals( null ) )
{
System.out.println( "hi" );
}
else
{
System.out.println( "hello" );
}
//check with if-else statement with = oprator
if ( date!= null )
{
System.out.println( "hi" );
}
else
{
System.out.println( "hello" );
}
}
public static Date showDate(){
return new Date();
}

Anand Pandey
- 383
- 4
- 12
-
3you're first check throws a null pointer exception if the object is actually null. the correct way to check it is with the == comparison. – Liam Clark Jan 22 '16 at 12:22
-8
You can check with an if-else statement, like this:
if (date.equals(null)) {
//something
} else {
//something
}
-
4If your date is null this results in a null pointer exception. – andrzej.szmukala Apr 19 '18 at 13:11