Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a warning for null == null?

Tags:

java

eclipse

Eclipse displays a warning when comparing two identical expressions :

if (1 == 1) -> warning
if (a == a) -> warning

However, no warning is shown for null == null (despite the fact that null == null is always true) :

if (null == null) -> no warning

Is there any reason for this ?

like image 675
merours Avatar asked Nov 20 '15 14:11

merours


People also ask

IS NULL reference possible?

[Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]


2 Answers

It helps to think about what this warning condition is trying to prevent. Its purpose is to warn you that you are not comparing the two variables you intended to compare, such as due to a typo (eg foo == foo when you meant foo == boo or foo == fpp), or two literal values (eg 1 == 1).

(Of course, comparing two literal values presents a different problem - the result will always be the same, and should just be simplified to true or false in the code anyway.)

null == null isn't a case of this potential problem. If you're naming a variable something close to "null" and then writing "null" by mistake, you've got an entirely different problem that no compiler can guess at.

like image 174
Martin Avatar answered Oct 31 '22 18:10

Martin


For primitive types like int and char, the value is known to the compiler. You can compare them and it is immediately picked up as identical values causing a warning.

For example:

'A' == 'A'

Or even:

'A' == 97

For objects, the value is not yet known to the compiler. It has not been allocated a space in memory where this value sits. The reference to the value needs to be checked at run-time even if it is the Null Reference.

For example:

null == null

or

"abc" == "abc"

However, you will get a warning for comparing an object to itself. This is because you have defined this object explicitly so the compiler knows it is identical without having to check its value.

like image 41
isak gilbert Avatar answered Oct 31 '22 18:10

isak gilbert