LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Predict the Output · Question 5

Values returned by compareTo Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("cat".compareTo("car") + " " + "car".compareTo("cart") + " " + "Zoo".compareTo("apple") + " "
                + "same".compareTo("same") + " " + "Zoo".compareToIgnoreCase("apple"));
    }
}
  • A 2 -1 -7 0 25 Correct
  • B 1 -1 -1 0 1
  • C 2 -1 25 0 -7
  • D -2 1 -7 0 25
Correct Answer: Option A

compareTo returns the difference of the first differing characters ('t' − 'r' = 2, 'Z' − 'a' = -7), or the difference in length when one string is a prefix of the other.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links