Page 266 - Cs_withBlue_J_C11_Flipbook
P. 266
The compareTo(String str) Function
This function compares the given string in the parameter with the string in the current object alphabetically. It returns
an integer type value, i.e., the value of the difference between the ASCII codes of the characters that are compared.
If both strings are equal, it returns 0. If the first string is larger lexicographically than the second string, it returns a
positive number else it returns a negative value.
Note: The ASCII value range is:
1. A to Z: 65 to 90
2. A to z: 97 to 122
3. 0 to 9: 48 to 57
The comparison is based on the first string.
if str1>str2 : it returns a positive value
if str1<str2 : it returns a negative value
if str1==str2 : it returns 0
The syntax is:
int <variable> = String_datatype_Variable.compareTo(String str);
Let us see the below example:
String wd1= "And";
String wd2= "and";
int value= wd1.compareTo(wd2);
System.out.println("Value: "+ value);
Output:
Value: -32 ( i.e., the difference between the ASCII codes of A and a = 65-97=-32, the comparison is between A and a, as
the first characters of both the strings are equal.)
Let us see the below example:
String str1= "INDIAN";
String str2= "INDIA";
int value= str1.compareTo(str2);
System.out.println("Value: "+ value);
Output:
Value: 1 ( since, str1 has one character extra than str2.)
Note: if str1= “INDIA” and str2=”INDIAN”, then compareTo() would have returned -1.
Let us see the below example:
String wd1= "Computer";
String wd2= "Computer";
int value= wd1.compareTo(wd2);
System.out.println("Value: "+ value);
Output:
Value: 0 ( since, both the strings are equal.)
The compareToIgnoreCase(String str) Function
This function is same as the compareTo() function. The only difference is that it compares the two strings without
checking the case of the letters. It returns an integer type value. The syntax is:
int <variable> = String_datatype_Variable.compareToIgnoreCase(String str);
264264 Touchpad Computer Science-XI

