Home » Java Tutorial » Compareto Java with Examples

Compareto Java with Examples

The java compareTo is a method used to compare two strings lexicographically. That means words of the string are sorted in alphabetical order and then the result is compared. The comparison is based on the character’s Unicode values. The compareTo method returns integer values. If both of the strings are equal then the java compareTo method returns 0. If the string is less than the other string (count of characters) then the returned value is negative. And if the string is greater than the other string (count of characters) then the returned value is positive.

How to use compareTo in java?

To use the CompareTo method java, create two objects of string that need to be compared. Access the compareTo method through the dot(.) operator with one object of string and pass the other object as a parameter to the method.

Check the examples below:

1. Comparing string using java compareTo method.

public class compare {
    public static void main(String[] args) {
        String s1 = "Welcome to Prad Tutorials";
        String s2 = "Welcome to Prad Tutorials";
        
        System.out.println(s1.compareTo(s2));
        
    }
    
}

Output

0

In the above code, the output is 0 that means both strings are equal.

2. Accepting strings from the user and comparing them using the java string compareTo method.

import java.util.Scanner;

public class compare {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first string: ");
        String s1 = sc.next();
        System.out.println("Enter the second string: ");
        String s2 = sc.next();
        
        if(s1.compareTo(s2) == 0)
        {
            System.out.print("Both the strings are equal");
        }
        else
        {
            System.out.print("Both the strings are not equal");
        }
        
    }
    
}

Output

Enter the first string: prad tutorials
Enter the second string: Welcome to prad tutorials
Both the strings are not equal

FAQ’s

What does compareto do in java?

The compareTo method sorts the string and then compares it. The compareTo method returns an integer value. 0 is both the strings are equal. Less than 0 if the first string’s characters are less than the second. And greater than 0 if the first string’s characters are greater than the second.

How does compareto work in java?

CompareTo method in java compares the string using lexicographically. That means words of the string are sorted in alphabetical order and then the result is compared.

Do you know?
1. Prime Number Program in Java
2. Type Casting In Java
3. Ternary Operator in Java
4. Immutable Class in Java
5 . Printf Java
6. While Loop Java
7. StringBuilder java
8. Binary Search Java
9. Encapsulation in java
10. Compareto Java

Pin It on Pinterest