-3

I tried the following code :

if (!object.equals(null)) {
                object.setItem(object1.getTime());
}

Here, object and object1 are objects of two classes.

The problem is that it enter into the statement for a null value.

Abhishek Ramachandran
  • 1,160
  • 1
  • 13
  • 34
  • 1
    Quoting javadoc of [`equals()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-): *For any non-null reference value `x`, `x.equals(null)` should return `false`.* And of course, `! false` is always `true`, so the `if` expression is, *by definition*, always `true`, which means the **`if` block will always be executed**. – Andreas Aug 27 '16 at 05:34
  • 3
    *"The problem is that it enter into the statement for a null value."* Don't see how it can do that, since the `object.equals(null)` expression will generate a `NullPointerException` if `object` is null, so the code inside the if block will never be reached. – Andreas Aug 27 '16 at 05:43

2 Answers2

5

For comparisons with null in Java, you use object != null

if(object != null){
  //
}
Durgpal Singh
  • 11,481
  • 4
  • 37
  • 49
Sterling
  • 322
  • 1
  • 7
1

The equals() method in Java compares two objects equality according to the equals() method contract which you have to override or it follows the Object class equals() method contract.

In any case, equals() method compares two objects. null is not an object. null is a reference type whose check should be done by using object != null.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
peendas
  • 11
  • 1