Question:

Which of the following String methods returns a negative value?

Show Hint

Remember: \texttt{compareTo()} returns \textbf{negative}, \textbf{zero}, or \textbf{positive} depending on dictionary order of strings. It is commonly used for lexicographical comparison.
  • length()
  • equals()
  • compareTo()
  • charAt()
Hide Solution
collegedunia
Verified By Collegedunia

The Correct Option is C

Solution and Explanation

Step 1: Understand what each String method returns.
In Java, different \texttt{String} methods return different types of values. Some methods return a number, some return a character, and some return a boolean value. To answer this question, we need to identify which method can return a negative integer value.
Step 2: Analyze each method one by one.
  • (A) \texttt{length():} This method returns the number of characters in a string. Since the length of a string can never be negative, it does not return a negative value.
  • (B) \texttt{equals():} This method compares two strings and returns either \texttt{true} or \texttt{false}. It does not return any numeric value.
  • (C) \texttt{compareTo():} This method compares two strings lexicographically. It can return:
    • a negative value if the first string comes before the second string,
    • zero if both strings are equal,
    • a positive value if the first string comes after the second string.
    So, this method can definitely return a negative value.
  • (D) \texttt{charAt():} This method returns the character present at a specified index in the string. It returns a character, not a negative number.
Step 3: Focus on \texttt{compareTo()}.
Suppose we compare: \[ \texttt{"Apple".compareTo("Banana")} \] Since \texttt{"Apple"} comes before \texttt{"Banana"} in dictionary order, the result will be a negative value. This shows clearly that \texttt{compareTo()} is the method that can return a negative value.
Step 4: Conclusion.
Therefore, among all the given String methods, the one that returns a negative value is \texttt{compareTo()}.
Final Answer:compareTo().
Was this answer helpful?
0
0

Questions Asked in ICSE Class X board exam

View More Questions