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); }
Topic: Return type errors and compareTo()
Answer
Statement with the error: boolean x = a.compareTo(b);
Corrected statement: int x = a.compareTo(b);
Output: -3
The compiler message names the fault exactly: an int cannot be stored in a boolean. compareTo() returns an int, so the variable holding its result must be declared int, not boolean. (equals() is the method that returns boolean — that is the distinction being tested.)
Now the value. compareTo() walks both strings together: K, I, N, G all match, and then "KING" runs out. When one string is a PREFIX of the other, the method returns the difference in lengths: 4 - 7 = -3. The negative sign shows "KING" comes first alphabetically.
Careful: some printed keys give -4 for this. Compile it and Java returns -3.