Page 353 - Computer science 868 Class 12
P. 353
if str1==str2: it returns 0
Syntax: int <variable> = Stringobject.compareTo(String str);
Example 1:
String str1= "India";
String str2= "INDIA";
int value= str1.compareTo(str2);
System.out.println("Value : "+ value);
Output:
Value: 32 ( i.e., the difference between the ASCII codes of n and N = 110-78=32. The comparison is between n and
N as the first characters of both the strings are equal. )
Example 2:
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.
Example 3:
String str1 = "INDIA";
String str2 = "INDIA";
int value = str1.compareTo(str2);
System.out.println("Value : "+ value);
Output:
Value: 0 ( since, both the strings are equal.)
16. int compareToIgnoreCase(String str): This method is same as the compareTo() method. The only difference is that
it is not case-sensitive. It doesn't check the case of the letters while comparing. It returns integer type value.
Syntax: int <variable> = Stringobject.compareToIgnoreCase(String str);
Example:
String str1 = "India";
String str2 = "INDIA";
int value = str1.compareToIgnoreCase(str2);
System.out.println("Value : "+ value);
Output:
Value : 0
17. boolean endsWith(String str): This method checks whether the string in the current object is ending with the
string in the parameter. This function returns a data type of the boolean value.
Syntax: boolean c <variable> = Stringobject.endsWith(String str);
Example:
String str1 = "India is my country";
String str2 = "try";
boolean b = str1.endsWith(str2);
if(b)
351
Strings 351

