Site icon TechVidvan

Java String compareTo() Method with Examples

The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string. It returns either a positive, negative, or 0.

The Unicode value of each character in the strings is used to compare the strings when comparing strings. Inferring the relative order of strings based on their character sequences is key.

Explanation

The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string. It returns either a positive, negative, or 0.

The Unicode value of each character in the strings is used to compare the strings when comparing strings.

A positive integer (difference of character value) is returned when the first string is lexicographically superior to the second string.

Syntax:

public int compareTo(String anotherString)

Parameter:

Return Value:

Example 1:

public class TechVidvanCompareTo {
    public static void main(String argvs[]) {
        String a1 = new String("INDIA IS MY COUNTRY");
        String a2 = new String("india is my country");
        System.out.println(a1.compareTo(a2));
    }
}

Output:

-32

Example 2:

public class TechVidvanCompareTo{  
public static void main(String args[]){  
String b1="Hello";  
String b2="";  
String b3="Everyone";  
System.out.println(b1.compareTo(b2));  
System.out.println(b2.compareTo(b3));  
}}

OUTPUT:

5
-7

Use of Java String CompareTo():

public class TechVidvanCompareTo{
    public static void main(String args[]) {
        String a1 = "hello";
        String a2 = "hello";
        String a3 = "meklo";
        String a4 = "hemlo";
        
        System.out.println(a1.compareTo(a2));
        System.out.println(a1.compareTo(a3));
        System.out.println(a1.compareTo(a4));
    }
}

Output:

0
-5
-1

Java allows us to compare Strings based on their content and references. It is used in reference matching (by the == operator), sorting (by the compareTo() method), and authentication (by the equals() method).

Diagram:

Types of Java compareTo():

The compareTo() method has three different iterations, which are as follows:

Technical details:

Case Sensitivity:

Uppercase and lowercase characters are regarded differently by compareTo() since it is case-sensitive.

Null handling:

NullPointerException will be thrown if either the invoking string or anotherString is null.

Exception from String CompareTo():

Advantages of Java String CompareTo():

Disadvantage of Java String CompareTo():

Conclusion

We have extensively discussed the CompareTo() function in Java. We briefly discussed the use of the CompareTo() method and then moved on to see how using this method can help reduce a significant amount of code in a program.

Exit mobile version