Solved 2024 Question Paper ICSE Class 10 Computer Applications — Question 28
Back to all questionsThe following code to compare two strings is compiled, the following syntax error was displayed – incompatible types – int cannot be converted to boolean.
Identify the statement which has the error and write the correct statement. Give the output of the program segment.
void calculate()
{
String a = "KING", b = "KINGDOM";
boolean x = a.compareTo(b);
System.out.println(x);
}boolean x = a.compareTo(b); has the error.
Corrected statement is:
boolean x = (a.compareTo(b) == 0);
false
Explanation
The error occurs in this line:
boolean x = a.compareTo(b);- The
compareTo()method of theStringclass returns anint, not aboolean. - The method compares two strings lexicographically and returns:
- 0 if the strings are equal.
- A positive value if the calling string is lexicographically greater.
- A negative value if the calling string is lexicographically smaller.
Since an int cannot be assigned to a boolean variable, this causes a "incompatible types" error.
To fix the error, we can use a comparison to convert the int result into a boolean:
boolean x = (a.compareTo(b) == 0); // True if strings are equalThis assigns true or false based on whether the two strings are equal.
Corrected Program:
void calculate() {
String a = "KING", b = "KINGDOM";
boolean x = (a.compareTo(b) == 0); // Check if strings are equal
System.out.println(x);
}Output of the Program:
"KING".compareTo("KINGDOM")compares the strings lexicographically."KING"is lexicographically smaller than"KINGDOM".- The result of
compareTo()will be -3 (difference between the lengths of the two strings ⇒ 4 - 7 = -3).
Since a.compareTo(b) == 0 is false, the output will be:
false