The difference between 'a == null' and 'null == a'

When you check if a variable is null, I saw that the proposed coding style is if(null == a) . What is the difference between this and if(a == null) ?

+6
source share
2 answers

No.

People sometimes write null == a for historical reasons, because it eliminates the possibility of typo errors in C. If you were to write:

 if (a = NULL) { // note, only single = ... 

in C, then this will execute the assignment operator a = NULL , with the result of the execution being the assigned value (i.e. NULL). Thus, instead of checking the value of a , you set it to NULL, and then essentially check if (NULL) , which is always false. It compiles, but it is almost certainly not what you want. And all this because of a small typo = vs == .

If you first set NULL , then if (NULL = a) is a compilation error, since you cannot assign a value to the constant that NULL represents.

There is no need for this in Java, since if (null) {... does not compile. (You can still have the same error in Java with boolean variables: if (someBooleanVar = someMethod()) . But this is a relatively rare pattern.)

This style is sometimes referred to as the " Yoda terms ," as it resembles the Yoda bizarre style in Star Wars.

+24
source

When comparing == no. See JLS for more details. For equals a.equals(null) , the equals method defined in class A with the null parameter is null.equals(a) , and null.equals(a) will be invalid.

However, you can also consider where one side of the comparison is not necessarily a null value, but is null. In this case ( notNull and nullable are both local variables and fields of reference type:

 notNull==nullable 

coincides with

 nullable==notNull 

but

 notNull.equals(nullable) 

should not throw a NullPointerException, and nullable.equals(notNull) will throw it if nullable is null.

+1
source

Source: https://habr.com/ru/post/982708/


All Articles