Sunday, January 4, 2009

Tips for String comparison in Java

Whenever we compare two strings objects in java, we normally consider both string arguments with qual importance and ignorance.I like to suggest one tip here which may be helpful for you in avoiding to generate a silly error, which looks terrible :)

I have two String objects as Str1 and Str2

Now i will compare two strings mentioned above for comparison, both may contain same value or may be having different values.

I have two options to write a conditional statement using equals opertator :

Type 1:
 if(Str1.equals(Str2))
  ...............
  ...............

Type 2:
 if(Str2.equals(Str1)) 
  ...............
  ...............

Which one you prefer.. i came across so many people explaining that its not that important to prefer which one i will opt for , as both produces same result.
Here i want to suggest you to analyze your code little bit, and reach a point where you can say, which String object cannot be null.If you found Str1 cannot be null , then use Str1.equals(Str2) , i.e. compare Str2 with Str1 , keeping Str1 at first place.
Reason for saying this is , if you are calling the equals method of the String object containing null value then it will through java.lang.NullPointerException.

So just by following a simple approache, you can avoid an exception.

There is another place where you can use this:
Whenever you are comparing a Constant String Object with a Dynamic String Object i.e. a string object which can contain different value while in the process of any kind. Please see the example mentioned below:-

String constant = "ENTRY_X";
Now i have a dynamic string object as dynamicStr, about whihc i am not sure, what type of value it can contain, then i will use:
if(constant.equals(dynamicStr))
........
.......

or 

if("ENTRY_X".equals(dynamicStr))
........
.......


This way i am avoiding the NullPointerException.
Its a very small tip, but i found this usefull information for all.
Please provide your comments if any.

If you liked my post, linking to this post will be highly appreciated.