String Methods

CompareTo

🙋 Need help? Ask an expert now!

The compareTo() method compares the first letter of one String object to the first letter of another String object and returns a number that states which String comes first in lexicographic order (A,B,C etc.). If the first two letters of the strings are the same, the method will go on to compare the next letters, and the next until it finds the first instance of a difference. Let's take a look at how this method works.

CompareToMethodExample.java
package exlcode;

public class CompareToMethodExample {

  public static String exampleVariableOne = "Ant";
  public static String exampleVariableTwo = "ant";
  public static String exampleVariableThree = "Butterfly";
  public static String exampleVariableFour = "Zebra";
  // compares the two Strings lexicographically and
  // assigns the difference to integer variables
  public static int exampleVariableFive = exampleVariableOne.compareTo(exampleVariableTwo);
  public static int exampleVariableSix = exampleVariableTwo.compareTo(exampleVariableOne);
  public static int exampleVariableSeven = exampleVariableThree.compareTo(exampleVariableOne);
  public static int exampleVariableEight = exampleVariableFour.compareTo(exampleVariableOne);

  public static void main(String[] args) {
    System.out.println(exampleVariableFive);
    System.out.println(exampleVariableSix);
    System.out.println(exampleVariableSeven);
    System.out.println(exampleVariableEight);
  }
}

The compareTo() method returns 0 if the two strings are equal, a number less than 0 if the first String is larger, and a number greater than 0 if the second String is larger. Uppercase letters come before lowercase letters when the method compares strings. As you work through learning this method's function, test our example program and use the ascii table to see how far apart the characters are from each other.

Application Question

Consider the following code segment:

String varOne = "Hello World!";
            String varTwo = "Java";
            System.out.println(varOne.compareTo(varTwo));
            

What is printed as a result of executing this code segment?