Computer Applications
Two strings, city1
and city2
, are compared using city1.compareTo(city2)
, and the result is less than zero. What does this indicate?
Answer
city1
appears before city2
in an alphabetical list.
Reason — The method compareTo(String s)
in Java compares two strings lexicographically. It returns:
- A negative value if the calling string (
city1
) comes before the argument string (city2
) in alphabetical order. - 0 if the two strings are equal.
- A positive value if the calling string (
city1
) comes after the argument string (city2
) in alphabetical order.
If the result is less than zero, it indicates that city1
appears before city2
lexicographically (alphabetically).
Related Questions
Write the output of the following String methods:
String x= "Galaxy", y= "Games";
(a) System.out.println(x.charAt(0)==y.charAt(0));
(b) System.out.println(x.compareTo(y));
A shopping website offers a special discount if the order ID has the sequence 555 anywhere in it. For example, 158545553031, 198555267140, …. .
Fill in the blanks (a) and (b) in the given Java Method to convert the order ID (a long integer) into a string and check if the sequence 555 is present in it.
void checkOrder(long oid) { String str = _______(a)_________; if(______(b)_______) { System.out.println("Special Discount Eligible: " + oid); } }
Write a program in Java to enter any sentence. Also ask the user to enter a word. Print the number of times the word entered is present in the sentence. If the word is not present in the sentence, then print an appropriate message.
The output of the statement "talent".compareTo("genius") is:
- 11
- –11
- 0
- 13