Saturday 14 June 2014

compareTo (String anotherString) : Compare two Strings

public int compareTo(String anotherString)
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. Return negative integer if this String object lexicographically precedes the argument string. Return positive integer if this String object lexicographically follows the argument string. Return zero if the strings are equal.

class StringCompareTo{
 public static void main(String args[]){
  String s1 = new String("abcd");
  String s2 = new String("efgh");
  String s3 = new String("abcd");
  
  System.out.println("s1 = " + s1);
  System.out.println("s2 = " + s2);
  System.out.println("s3 = " + s3);
  
  System.out.println("s1.compareTo(s2) = " + s1.compareTo(s2));
  System.out.println("s2.compareTo(s1) = " + s2.compareTo(s1));
  System.out.println("s1.compareTo(s3) = " + s1.compareTo(s3));
 }
}

Output
s1 = abcd
s2 = efgh
s3 = abcd
s1.compareTo(s2) = -4
s2.compareTo(s1) = 4
s1.compareTo(s3) = 0

1. Throws NullPointerException if anotherString is null.
class StringCompareToNull{
 public static void main(String args[]){
  String s1 = new String("abcd");
  
  System.out.println("s1 = " + s1);

  System.out.println("s1.compareTo(null) = " + s1.compareTo(null));
 }
}

Output
s1 = abcd
Exception in thread "main" java.lang.NullPointerException
        at java.lang.String.compareTo(String.java:1142)
        at StringCompareToNull.main(StringCompareToNull.java:7)





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment