Sunday 3 April 2011

How to Compare String in java

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

No comments:

Post a Comment