What is the difference between str.equals(''Vicky'') and ''Vicky''.equals(str) in Java?

UPDATED: 14 October 2014
javaQuery


String Comparison
Comparing one string value against another string value either matching same case or ignoring its case. Its much important that How you're comparing Strings.

Source Code
Lets consider following code...
public class CompareString {
    private String Firstname;
    public static void main(String[] args) {
        /* Create an Object of CompareString */
        CompareString objCompareString = new CompareString();
        /* Set null value for Firstname */
        objCompareString.setFirstname(null);
        /* Get value in local variable */
        String name = objCompareString.getFirstname();
        /**
         * Compare string
         * java.lang.NullPointerException will occur in this case
         */
        if (name.equals("Vicky")) {
            System.out.println("Fail");
        }

        /**
         * Compreare string
         * It will handle java.lang.NullPointerException without checking null
         */
        if ("Vicky".equals(name)) {
            System.out.println("Passed");
        }
    }

    /**
     * Getter of Firstname
     * @return 
     */
    public String getFirstname() {
        return Firstname;
    }

    /**
     * Setter of Firstname
     * @param Firstname 
     */
    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }
}

Case 1: name.equals("Vicky") Compare unknown value with known value.
We are comparing name(unknown) value with another string Vicky(known) value. name will be decided based on some database call, calling another method, etc... It may possible you get null value of name and possible chances of java.lang.NullPointerException or you have to check explicitly for null value of name.

Case 2: "Vicky".equals(name) Compare known value with unknown value.
We are comparing Vicky(known) value with another string name(unknown) value. Same way name will be decided based on some database call, calling another method, etc... But equals and equalsIgnoreCase method of String will handle the null value and you don't have to check explicitly for null value of name.


Why "Vicky".equals(name) Compare known value with unknown value handles null.
To understand the core logic I extracted code of equals and equalsIgnoreCase method from String class.
/* Original source code form String class */
public boolean equals(Object anObject) {
 if (this == anObject) {
     return true;
 }
 /* This condition handles null value */
 if (anObject instanceof String) {
     String anotherString = (String)anObject;
     int n = count;
     if (n == anotherString.count) {
  char v1[] = value;
  char v2[] = anotherString.value;
  int i = offset;
  int j = anotherString.offset;
  while (n-- != 0) {
      if (v1[i++] != v2[j++])
   return false;
  }
  return true;
     }
 }
 return false;
}
anObject instanceof String implemented as null instanceof String and because null is not instance of String so It'll return false.
/* Original source code form String class */
public boolean equalsIgnoreCase(String anotherString) {
 return (this == anotherString) ? true : (anotherString != null) && (anotherString.count == count) && regionMatches(true, 0, anotherString, 0, count);
}
(anotherString != null) handles null value.

Interview Question
This is one of the popular question asked in Interviews. Those who knows answer says...

Ordinary Answer: Comparing known value with unknown value handles null.
ExtraOrdinary Answer: Comparing known value with unknown value handles null because null is not instance of String in case of equals and in case of equalsIgnoreCase, it checks the null before comparison.

Conclusion:
Always compare known value with unknown value to handle the null and to avoid the java.lang.NullPointerException.

0 comments :