Monday 13 July 2015

Compare two Strings

equals() method.

equalsIgnoreCase() method.

compareTo() method.

compareToIgnoreCase() method.

compare() method : write a Comparator by implementing Comparator interface.

Comparing String using compareTo
Returns zero if two Strings are same, less than zero if calling string comes before argument string and greater than zero if calling string comes later than argument string as shown in example below.

Compare String using compareToIgnoreCase
Similar to compareTo() method with ignoring case like equalsIgnoreCase() and return same values as returned by compareTo during String comparison.

public class StringComparisonExample {
       public static void main(String args[]) {
              String str1 = "javaExplorer";
              String str2 = "javaExplorer";

              // String compare example using equals
              System.out.println(str1.equals(str2));

              // String compare example in java using compareTo
              if (str1.compareTo(str2) == 0) {
                     System.out.println("Equal: compareTo method!!");
              }

              str2 = "JAVAEXPLORER";

              // Java String comparison example using equalsIgnoreCase
              if (str1.equalsIgnoreCase(str2)) {
                     System.out.println("Equal: equalsIgnoreCase method!!");
              }

              // String comparison example in java using CompareToIgnoreCase
              if (str1.compareToIgnoreCase(str2) == 0) {
                     System.out.println("Equal: compareToIgnoreCase method");
              }

              String str3 = "Java";
              String str4 = "Jug";

              // lexicographical comparison of String in Java with ComapreTo
              if (str3.compareTo(str4) > 0) {
                 System.out.println("Java after Jug:lexicographical order");
              } else if (str3.compareTo(str4) < 0) {
                 System.out.println("Java before Jug:lexicographical order");
              }
       }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...