Java String Comparison: compareTo() Guide
– In Java, you can use the compareTo() method to compare the sizes of two strings. This method, belonging to the String class, serves to determine the relative size of two strings.
The comparison rules are as follows:
- Return 0 if the two strings are equal.
- If the first string is less than the second string, return a negative integer.
- Return a positive integer if the first string is greater than the second string.
Here is an example code comparing the sizes of two strings:
String str1 = "abc";
String str2 = "def";
int result = str1.compareTo(str2);
if(result < 0) {
System.out.println("str1小于str2");
} else if(result > 0) {
System.out.println("str1大于str2");
} else {
System.out.println("str1等于str2");
}
The above code will output “str1 is less than str2” because in the alphabet, “abc” comes before “def”.