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);
}
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 theString
class 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 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
Related Questions
Consider the following two-dimensional array and answer the questions given below:
int x[ ][ ] = {{4,3,2}, {7,8,2}, {8, 3,10}, {1, 2, 9}};
(a) What is the order of the array?
(b) What is the value of x[0][0]+x[2][2]?
Differentiate between boxing and unboxing.
Consider the given program and answer the questions given below:
class temp { int a; temp() { a=10; } temp(int z) { a=z; } void print() { System.out.println(a); } void main() { temp t = new temp(); temp x = new temp(30); t.print(); x.print(); } }
(a) What concept of OOPs is depicted in the above program with two constructors?
(b) What is the output of the method main()?
Primitive data types are built in data types which are a part of the wrapper classes. These wrapper classes are encapsulated in the java.lang package. Non primitive datatypes like Scanner class are a part of the utility package for which an object needs to be created.
(a) To which package the Character and Boolean classes belong?
(b) Write the statement to access the Scanner class in the program.