Skip to Content

Java String Compare Example

  1. /*
  2. Java String compare example.
  3. This Java String compare example describes how Java String is compared with another
  4. Java String object or Java Object.
  5. */
  6.  
  7. public class JavaStringCompareExample{
  8.  
  9.   public static void main(String args[]){
  10.  
  11.   /*
  12.   Java String class defines following methods to compare Java String object.
  13.   1) int compareTo( String anotherString )
  14.   compare two string based upon the unicode value of each character in the String.
  15.   Returns negative int if first string is less than another
  16.   Returns positive int if first string is grater than another
  17.   Returns 0 if both strings are same.
  18.   2) int compareTo( Object obj )
  19.   Behaves exactly like compareTo ( String anotherString) if the argument object
  20.   is of type String, otherwise throws ClassCastException.
  21.   3) int compareToIgnoreCase( String anotherString )
  22.   Compares two strings ignoring the character case of the given String.
  23.   */
  24.  
  25.   String str = "Hello World";
  26.   String anotherString = "hello world";
  27.   Object objStr = str;
  28.  
  29.   /* compare two strings, case sensitive */
  30.   System.out.println( str.compareTo(anotherString) );
  31.   /* compare two strings, ignores character case  */
  32.   System.out.println( str.compareToIgnoreCase(anotherString) );
  33.   /* compare string with object */
  34.   System.out.println( str.compareTo(objStr) );
  35.  
  36.   }
  37.  
  38. }
  39.  
  40. /*
  41. OUTPUT of the above given Java String compare Example would be :
  42. -32
  43. 0
  44. 0
  45. */