Home > Programming > A good practice to Compare String in Java

A good practice to Compare String in Java

December 7th, 2008 Leave a comment Go to comments

Many people confused or don’t understand the concept to use String object properly.
In most case, when they try to compare 2 identical string objects they don’t get matching result.

When you have to do string comparison, there are few points to remember:

  • These operators <, <=, >, or >= cannot be used
  • These operator == and != don’t compare character in the string or string outside String pool. Only use these operator when you want to check if String value is NULL
  • Use String .equals , String .compareTo and Collator .compare to get accurate comparison result. Use these operators when String value is not NULL

The following class demonstrate how string are being compare in different way and the result of each

import java.text.Collator;
 
public class TestCompareObject {
 
  public static void main(String[] args) {
      String s1 = "Same String Value but could be different result";
      String s2 = "Same String Value but could be different result";
      String s3 = new String ("Same String Value but could be different result");
      Collator c = Collator.getInstance();
 
      System.out.println("1. s1 == s2 ? : " + (s1 == s2 ? "true" : "false"));
      System.out.println("2. s1 == s3 ? : " + (s1 == s3 ? "true" : "false"));
      System.out.println("2. s1.compareTo(s3) : " +
              (s1.compareTo(s3) == 0 ? "equal" : "not equal"));
      System.out.println("3. s1.equals(s3) : " +
              (s1.equals(s3) ? "true" : "false"));
 
      int c_compare = c.compare(s1, s3);
      System.out.println("4. Collator compare(s1, s3) ? : " +
              (c_compare == 0 ? "equal" : "not equal") );
  }
 
}

Below is the output of this program

1. s1 == s2 ? : true
2. s1 == s3 ? : false
2. s1.compareTo(s3) : equal
3. s1.equals(s3) : true
4. Collator compare(s1, s3) ? : equal
Categories: Programming
  1. No comments yet.
  1. No trackbacks yet.