Computer Applications

The 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);
}

Java String Handling

ICSE 2024

10 Likes

Answer

boolean x = a.compareTo(b); has the error.

Corrected statement is:

boolean x = (a.compareTo(b) == 0);

Output
false

Explanation

The error occurs in this line:

boolean x = a.compareTo(b);
  • The compareTo() method of the String class returns an int, not a boolean.
  • 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 equal

This 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

Answered By

6 Likes


Related Questions