×

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax:
public int compareTo(String anotherString)
Parameters: anotherString: the String to be compared with the current String Returns: An integer value based on the case. compare two Strings i.e. s1 and s2 if s1 > s2, it returns positive number if s1 < s2, it returns negative number if s1 == s2, it returns 0 Java String compareTo() Example 1:
public class CompareToEx1
{ 
public static void main(String args[]){ 
         String s1="tutorial"; 
         String s2="Tutorial"; 
         String s3="tootorial"; 
         String s4="tutorial"; 
        String s5="tooturial"; 
       System.out.println(s1.compareTo(s2));
       System.out.println(s1.compareTo(s3));
       System.out.println(s1.compareTo(s4));//0 because both are equal    
      System.out.println(s1.compareTo(s5));
}
}
Output:
32
6
0
6
Java String compareTo() Example 2:
public class CompareToEx2
{
    public static void main(String[] args)
    {
        //compare a String
        String str = "Java TutorialAndExample";
        System.out.println("Compare To : " + str.compareTo("JAVA TUTORIALANDEXAMPLE"));
        //Compare a String with Ignore case
        System.out.println("Compare To : " + str.compareToIgnoreCase("JAVA TUTORIALANDEXAMPLE"));
    }
}
OUTPUT:
Compare To : 32
Compare To : 0
Java String compareTo() Example 3:
public class CompareToEx3 {
    public static void main(String[] args) {
        String s1,s2,s3,s4;
         s1 = "tutorial";
         s2 = "tutorial2";
         s3 = "TUTORIAL";
        System.out.println("String 1: " + s1);
        System.out.println("String 2: " + s2);
        System.out.println("String 3: " + s3);        
        // Compare the strings s1 and s2.  
        int S = s1.compareTo(s2);
        // Show the results of the comparison.  
        if (S < 0) { 
             System.out.println(s1 +"  is lexicographically greater than  " +  s2 );
          //compare the string s1 and s3 
           int s = s1.compareTo(s3.toLowerCase());
             if (s < 0) { 
             System.out.println( s1 +  " is lexicographically greater than " + s3 );
            } else if (s == 0) {
            System.out.println(s1 + " is lexicographically  equal to " + s3 );
        } else if (s > 0) {
            System.out.println( s1 + " is lexicographically less than " + s3 );
        } 
          } else if (S == 0) {
            System.out.println(s1 + " is lexicographically  equal to " +  s2 );
        } else if (S > 0) {
            System.out.println( s1 + " is lexicographically less than " +  s2 );
        } 
  }
Output:
String 1: tutorial
String 2: tutorial2
String 3: TUTORIAL
"tutorial" is lexicographically greater than "tutorial2"
"tutorial" is lexicographically  equal to "TUTORIAL"

Related Topics

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.