Java String compareTo() Method

What is String?

In Java, an string class is a series of characters that are interpreted literally by a script. The string can be either only letters or be letters and numbers in most programming languages. For example,  “PrepInsta” is a string containing a sequence of characters ‘P’, ‘r’, ‘e’ , ‘p’ , ‘I’, ‘n’, ‘s’ , ‘t’, ‘a’

To know more about String Class in java read the complete article.

 

String compareTo() Method

The main work of java string class compareTo() is to compare the string with the comment string lexicographically. It returns a positive number, negative number, or 0.

Note: The given string and the current string is compared on the basis of the Unicode value of each character present in the string.

  • If it is impossible to compare this item to the specified object, a ClassCastException is thrown.
  • If the specified object is null, a NullPointerException is thrown.

Syntax:

 public int compareTo(String anotherString)

Parameters:

 anotherString - the String to be compared.

Let’s look at a string-related Java program where the compareTo() method is used to perform an operation on the given string.

Examples : Comparing two given strings

Run
public class Main {
  public static void main(String[] args) {
    String myStr1 = "PrepInsta";
    String myStr2 = "PrepInsta";
    System.out.println(myStr1.compareTo(myStr2)); // Returns 0 because they are equal
  }
}

Output

0

Examples : Comparing two given strings

Run
public class Main {
  public static void main(String[] args) {
    String myStr1 = "PrepInsta";
    String myStr2 = "PrepInsta Prime";
    System.out.println(myStr1.compareTo(myStr2)); // Returns negative value
  }
}

Output

-6
Java String compareToIgnoreCase() Method

Examples : Comparing two given strings

Run
public class Main {
  public static void main(String[] args) {
    String myStr1 = "PrepInsta Prime";
    String myStr2 = "PrepInsta";
    System.out.println(myStr1.compareTo(myStr2)); // Returns Positive value
  }
}

Output

7

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription