Compare two string in Java

Following example compares two strings by using str compareTo (string) , str compareToIgnoreCase(String) and str compareTo(object string) of string class and returns the ascii difference of first odd characters of compared strings .
Code snippet
public class StringCompare{
   public static void main(String args[]){
     
      String str1 = "Hello World";
      String str2 = "hello world";
      Object objStr = str1;
    
      if(str1.compareTo(str2)==0){
         System.out.println("Strings are equal");
      }else{
         System.out.println("Strings are not equal");
      }
     
      if(str1.compareToIgnoreCase(str2)==0){
         System.out.println("Strings are equal");
      }else{
         System.out.println("Strings are not equal");
      }
     
      if(str1.compareTo(objStr.toString())==0){
         System.out.println("Strings are equal");
      }else{
         System.out.println("Strings are not equal");
      }
   }
}




Output



The above code sample will produce the following result.












Strings are not equal


Strings are equal


Strings are equal


Sourcecode Download