• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
prince davies
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Radhakrishna Sharma Gorenta
Ranch Hand
Posts: 63
Google App Engine Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic