my dog learned polymorphism*
The moose likes Java in General and the fly likes comparing two values with equalsIgnoreCase and equals with NULL as first value. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "comparing two values with equalsIgnoreCase and equals with NULL as first value." Watch "comparing two values with equalsIgnoreCase and equals with NULL as first value." New topic
Author

comparing two values with equalsIgnoreCase and equals with NULL as first value.

prince davies
Ranch Hand

Joined: May 08, 2009
Posts: 74


The above code returns me NULL POINTER EXCEPTION ,since the first element in the equalsIgnoreCase and equals is a null;
Why does it throw Null Pointe Exception?


java.lang.NullPointerException
at EqualIgnoreForNull.main(EqualIgnoreForNull.java:11)
Exception in thread "main"





HERE the second element in the equalsIgnoreCase and equals is null and the first element has value,but it does not throw NullPointerException
Why it does behave like this?
it returns me values.
different
different1


How do I compare two values?
If one is null and other has values,if these are assigned at run time ; how do I compare with equalsIgnoreCase and equals() ?

Apparently null is different from any other value,so I HAVE TO EXPECT null and other values in both elements. This happends for only first element.

How do I write a refined code for comparing two values considering or expecting null ?

if I use the following way,its not correct


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38467
    
  23
Find the java.util.Objects class, which has equals() methods overloaded to take two parameters, and can cope with null values. Beware: it is only available in Java7. Or you can use an if (x != null) ... test.
rk sharma
Ranch Hand

Joined: Jun 25, 2011
Posts: 50

Hello Davies,
You should not call equals() method using the reference which points to "null".
In the first case yo will get NullPointerException obviously. but the second approach is correct. see the java SE API.


Regards,

RK
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: comparing two values with equalsIgnoreCase and equals with NULL as first value.