-2

Please help me with these java syntax issue.

I know obj.equals(null) is wrong, so whats the correct way to write an expression like

 if(!obj.equals(null)){
 some code    
}

I am confused between option 1

if(!(obj == null)){
some code
}

and the other option 2

if(obj != null){
some code
}

There's one more, for an expression like

    if(obj.equals(null) || obj2.equals(obj3))

am I correct if I write

if(obj == null || obj2.equals(obj3)) 

or should this be different ?

sweetu514
  • 65
  • 1
  • 18

4 Answers4

1

As you are verifying whether the reference is null or not, then use this:

if(obj != null){
}

or

if(!(obj == null)){
}
Diego Urenia
  • 1,620
  • 2
  • 21
  • 28
1

Options 1 and 2 are logically equivalent. I'd prefer Option 2, it's more concise.

if(obj == null || obj2.equals(obj3)) is best because you avoid the possibility of calling a function on a null object.

Kukanani
  • 718
  • 1
  • 6
  • 22
0
 public boolean equals(Object obj) {
        return (this == obj);
    }

thats the actual Object#equals implementation. They all are logically equivalent.

Except that if calling Object object is null, object.equals() will throw an NPE.

rocketboy
  • 9,573
  • 2
  • 34
  • 36
0

These are logically equivalent, meaning they will resolve the same way:

if(!(obj == null)){
    //some code
}


if(obj != null){
   //some code
}

If the object is null, this will result in a null pointer exception:

if(obj.equals(null) || obj2.equals(obj3))

This say if an object is null or if obj2 equals obj3, then execute a block of code.

if(obj == null || obj2.equals(obj3)) 
Pete B.
  • 3,188
  • 6
  • 25
  • 38