8

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.

maman
  • 107
  • 1
  • 1
  • 6

4 Answers4

17

Check if it is null:

if (date == null) {...}

Check if it is not null:

if (date != null) {...}
James
  • 1,471
  • 3
  • 23
  • 52
  • 3
    Tip: 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
  • 3
    you'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
}
N3dst4
  • 6,360
  • 2
  • 20
  • 34
Raju
  • 448
  • 1
  • 9
  • 24