Wednesday, June 18, 2014

String comparison tip

In Java if you actually want to test whether two strings have the same value you should use .equals(). It checks value equality. I think most of the people knew it. 

Today I want to add a very valuable tip:
If you have strings or constants to compare, always put them first in the equals clause. 
//StringComparisonTip.java
public class StringComparisonTip {
   public static void main(String[] args) {
     // Recommended String comparison
     if("Venkatesh".equals(getMyName())){  
        System.out.println("We are equal");
     }
     // It is Correct but it may be throws NPE at runtime
     if(getMyName().equals("Venkatesh")){  
        System.out.println("We are equal");
     }
   }
   public static String getMyName(){
     return null;
   }
}
In the above code line #5 (if("Venkatesh".equals(getMyName()))) is much better than the line #9 (if(getMyName().equals("Venkatesh"))) because in the second case getMyName() may be null and throws an java.lang.NullPointerException while in the first case it doesn't matter if getMyName() is null. 

Note: I am not saying second one is wrong but I am saying it is not recommended by Java Guru's(Who has great knowledge in Java). Both are syntactically correct and you never get compilation error.

2 comments:

  1. right....."String_literal_to_be_matched".equals(String_object_given_by_user)...

    ReplyDelete
  2. I liked this tip. Thanks Venkatesh!!

    ReplyDelete