Online Tutorials & Training Materials | STechies.com
Register Login

String compareTo() Method in Java

|| 0

String compareTo() Method in Java
Stechies

We use Java string compareTo() method to compare two strings, but this comparison can be done in a different way. Before the comparison of strings, each character of the strings is converted into a Unicode, this method is known as a lexicographical method. This lexical order compares alphabetically, means the method do the sequential comparison of letters alphabetically which are placed in the string.

If the comparison of strings is equal, then return value 0, else it will return either a positive or a negative values. A positive integer is returned if the first string Unicode total is less than the second string Unicode total, otherwise it will return the Negative value.

This method is defined in the java.lang.comparable.

Syntax :

public int compareTo (String Str)

*where str is a string , this method takes only one string.

Method Returns values:

The method returns is an integer value, which is based on the lexicographical comparison between two strings.

* if string 1 > string 2, it returns negative number.
* if String 1 < srting 2, it returns positive number.
* if String 1 == String 2, it returns 0.

Example 1

// Java code to demonstrate how to work compareTo() function 

public class ExampleToCmp { 
public static void main(String args[]){
		// Initializing Strings
		String str1 = "computer";
		String str2 = "computer"; 
		String str3 = "aakash";

		// Checking if computer equals to computer string
		System.out.print("Difference of computer(str) and computer 	(str) : ");
		System.out.println(str1.compareTo(str2)); 

		// Checking if computer string equals to Aaksh string
		System.out.print("Difference of Aakash(str) and computers(str) : ");
		System.out.println(str1.compareTo(str3)); 
	}
}

Output:

Difference of computer(str) and computer(str) : 0
Difference of Aakash(str) and computers(str) : 2

Example 2

public class Comp_String {
    public static void main(String[] args) {
        String str_1 = "A";
        System.out.println("Compare To 'A' b is : " + str_1.compareTo("B"));
        str_1 = "B";
        System.out.println("Compare To 'B' a is : " + str_1.compareTo("A"));
        str_1 = "B";
        System.out.println("Compare To 'B' b is : " + str_1.compareTo("B"));
    }
}

Output:

Compare To 'A' b is : -1
Compare To 'B' a is : 1
Compare To 'B' b is : 0

 


Related Articles