Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if (a != null && a instanceof A) ... or if (a instanceof A)

Tags:

java

For the following conditionals:

if (a != null && a instanceof A)

or

if (a instanceof A)

Is there any advantage (for example, performance-wise) to check for null first? Both conditionals should be equal in result.

like image 344
Dmitriy Avatar asked Jul 25 '10 05:07

Dmitriy


People also ask

What does != null mean in Java?

Null means nothing. No object. At all. A null value can be assigned to an object reference of any type. Null can be cast to any type as it can be assigned to an object reference of that type.

How do you use an if statement with null?

Use an "if" statement to create a condition for the null. You can use the boolean value as a condition for what the statement does next. For example, if the value is null, then print text "object is null". If "==" does not find the variable to be null, then it will skip the condition or can take a different path.

Is equalsIgnoreCase null safe?

equalsIgnoreCase(String) is null-safe with literal string on left side of method' completed without exception!

Can you use == for null?

equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null .


2 Answers

No advantage whatsoever, you can just do with

if(a instanceof A) {}

this will return evaluate to false if a is null

like image 59
naikus Avatar answered Oct 11 '22 13:10

naikus


if(a instanceof A) is enough.

The if(a!=null && expr) pattern is used when expr will throw a NullPointerException if a is null. a instanceof A doesn't throw a NPE and just returns false if a is null.

like image 35
samitgaur Avatar answered Oct 11 '22 12:10

samitgaur