Java compareTo Method
Java compareTo Method
The Java compareTo() method compares values lexicographically and returns an integer value that describes if the first string is less than, equal to, or greater than the second string.
Suppose str1 and str2 are two string variables.
str1 == str2 :0
str1 > str2 : positive value
str1 < str2 : negative value
Example
Let’s understand the compareTo() method with the help of an example
program:
package com.testingdocs.stringmethods;
public class ExampleProgram {
public static void main(String[] args) {
String str1 = "abcd";
String str2 = "abcd";
String str3 = "wxyz";
// compareTo() method demo
System.out.println(str1.compareTo(str2));
System.out.println(str1.compareTo(str3));
System.out.println(str3.compareTo(str1));
}
}
Program Output
The program output is as follows:
0
-22
22
Java Tutorials
Java Tutorial on this website:
For more information on Java, visit the official website :