Notes
In Apex, the compareTo()
method is used to compare two String objects lexicographically. It returns an integer value indicating the relationship between the two strings. Here's a brief overview:
Here's an example:
String str1 = 'Apple';
String str2 = 'Banana';
Integer result = str1.compareTo(str2);
if (result < 0) {
System.debug('str1 is less than str2');
} else if (result == 0) {
System.debug('str1 is equal to str2');
} else {
System.debug('str1 is greater than str2');
}
-
Return Values:
- Returns a negative integer if the calling string is lexicographically less than the specified string (
otherString
).
- Returns zero if the calling string is lexicographically equal to the specified string.
- Returns a positive integer if the calling string is lexicographically greater than the specified string.
-
Explanation:
- In the example, it will print 'str1 is less than str2' because 'Apple' is lexicographically less than 'Banana'.
-
Note:
- The comparison is case-sensitive; uppercase letters have a different ASCII value than their lowercase counterparts.
- If you want a case-insensitive comparison, you might convert both strings to lowercase (or uppercase) before using
compareTo()
.
Video
Video does not exists.