Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java String Compare Example

  1. /*
  2. Java String compare example
  3. This Java String compare example describes how Java String is
  4. compared with another 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.        
  14.         1) int compareTo(String anotherString)
  15.         compare two string based upon the unicode value of each character in the String.
  16.         Returns negative int if first string is less than another. Returns positive
  17.         int if first string is grater than another and returns 0 if both strings are same.
  18.        
  19.         2) int compareTo(Object obj)        
  20.         Behaves exactly like compareTo(String anotherString) if the argument
  21.         object is of type String, otherwise throws ClassCastException.
  22.        
  23.         3) int compareToIgnoreCase(String anotherString)        
  24.         Compares two strings ignoring the character case of the given String.
  25.         */
  26.        
  27.         String str = "Hello World";        
  28.         String anotherString = "hello world";        
  29.         Object objStr = str;
  30.        
  31.         /* compare two strings, case sensitive */        
  32.         System.out.println(str.compareTo(anotherString));
  33.        
  34.         /* compare two strings, ignores character case  */        
  35.         System.out.println(str.compareToIgnoreCase(anotherString));
  36.        
  37.         /* compare string with object */        
  38.         System.out.println(str.compareTo(objStr.toString()));
  39.        
  40.     }
  41.  
  42. }
  43.  
  44. /*
  45. OUTPUT of the above given Java String compare Example would be:
  46. -32
  47. 0
  48. 0
  49. */
Your rating: None Average: 5 (1 vote)
Share this
Anonymous's picture

thanks

thanks
Anonymous's picture

thanks a lot ;) :)

thanks a lot ;) :)
Anonymous's picture

its very useful to me..

its very useful to me..
Anonymous's picture

Same for me. just read that

Same for me. just read that compareTo() method of comparable class should be in sync with equals() method , does it valid for string as well ? What is the disadvantage if its not ?
Anonymous's picture

awesome

awesome
Anonymous's picture

it was really useful..

it was really useful..
Anonymous's picture

tnks for ur suggestions

tnks for ur suggestions

Post new comment