Java Program To Compare Strings Using compareTo Function

01. Example:

public class stringComparison {
   public static void main(String args[]) {
       
      String string01 = "zeroones";
      String string02 = "Zeroones";
      String string03 = "zero one";
      String string04 = "zeroones";
      
      System.out.println(string01.compareTo(string02));  // Output will be 32 because "Z" ASCII value is 90 and 'z' ASCII value is 122. (122 - 90 = 32)
      System.out.println(string01.compareTo(string03));  // Output will be 79 because "space" ASCII value is 32 and 'o' ASCII value is 111. (111 - 32 = 79)
      System.out.println(string01.compareTo(string04));  // Output will be zero because both string are same
   }
}

Output:

32
79
0

Leave a comment