Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should null == null be true when comparing objects?

I'm curious what everyone thinks. In SQL (at least in oracle) NULL translates conceptually to "I don't know the value" so NULL = NULL is false. (Maybe it actually results in a NULL which then gets cast to false or something like that...)

This makes sense to me, but in most OO languages null means "no reference" so null==null should probably be true. This is the usual way of doing things in C# for example when overriding Equals.

On the other hand, null is still frequently used to mean "I don't know" in object-oriented languages and implementing null==null to false might result in code that is slightly more meaningful to certain domains.

Tell me what you think.

like image 869
George Mauer Avatar asked Nov 03 '09 02:11

George Mauer


People also ask

IS null == null true in Java?

To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.

Can you compare null null?

In SQL null is not equal ( = ) to anything—not even to another null . According to the three-valued logic of SQL, the result of null = null is not true but unknown. SQL has the is [not] null predicate to test if a particular value is null .

Can you use == for null?

Code Correctness: null Argument to equals()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 . (If the object is null , the program will throw a NullPointerException ).

Can null values be compared State True or false?

Comparisons to null The SQL null value basically means “could be anything”. It is therefore impossible to tell whether a comparison to null is true or false. That's where the third logical value, unknown, comes in. Unknown means “true or false, depending on the null values”.


2 Answers

For general purpose programming, null == null should probably return true.

I can't count the number of times I've run into the

if( obj != null )
{
   //call methods on obj
}

pattern, and it often seems unavoidable. If null == null evaluated to false, this pattern would fall apart, and there wouldn't be a good way to handle this case without exceptions.

like image 172
Stefan Kendall Avatar answered Oct 21 '22 04:10

Stefan Kendall


I think that null in Java, just like NULL in C++ or None in Python, means specifically "there's nothing here" -- not "I don't know", which is a concept peculiar to SQL, not common in OOP languages.

like image 27
Alex Martelli Avatar answered Oct 21 '22 03:10

Alex Martelli