In Java, an string class is a series of characters that are interpreted literally by a script. The string can be either only letters or be letters and numbers in most programming languages. For example, “PrepInsta” is a string containing a sequence of characters ‘P’, ‘r’, ‘e’ , ‘p’ , ‘I’, ‘n’, ‘s’ , ‘t’, ‘a’
To know more about String Class in java read the complete article.
String compareTo() Method
The main work of java string class compareTo() is to compare the string with the comment string lexicographically. It returns a positive number, negative number, or 0.
Note: The given string and the current string is compared on the basis of the Unicode value of each character present in the string.
Returns 1. The outcome is a negative integer if the first string's lexical length is shorter than the second string's
2. The outcome is a Positive integer if the first string is lexicographically longer than the second string.
3. The result is zero if it is lexically equal to the second string.
If it is impossible to compare this item to the specified object, a ClassCastException is thrown.
If the specified object is null, a NullPointerException is thrown.
public class Main {
public static void main(String[] args) {
String myStr1 = "PrepInsta";
String myStr2 = "PrepInsta";
System.out.println(myStr1.compareTo(myStr2)); // Returns 0 because they are equal
}
}
Output
0
Note:Here the output comes is 0 because the both the strings given in the code is equal.
Login/Signup to comment