Thursday, September 3, 2009

Is null == null?

This is a classic question that every developer has faced. Well I guess it depends on how we define null. Theoretically null is definitely not equal to another null. But pragmatically it is considered so in many cases. Databases will not allow direct comparison of null. We will have to use the statement "is null" to do check for null values from a database point of view.

Try the following java code snippet:
System.out.println(null == null); //Evaluates to true
Object a = null;
Object b = null;
System.out.println(a == b); //Evaluates to True
System.out.println(a.equals(b)); //Null Pointer Exception


When we use == operator for objects, it looks whether both objects point to the same reference (In this case which Java accepts as true based on our previous test). Whereas when we call equals, it checks to see if the references to the object are the same. The references are null, so we get a Null Pointer Exception.

No comments:

Post a Comment