Bird
0
0

What will be the output of the following Java code?

medium📝 Predict Output Q13 of 15
Java - Strings and String Handling
What will be the output of the following Java code?
String a = "apple";
String b = "banana";
int result = a.compareTo(b);
System.out.println(result > 0 ? "a > b" : "a <= b");
Aa > b
Ba <= b
C0
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand compareTo() behavior

    compareTo() returns a negative number if the first string is alphabetically before the second.
  2. Step 2: Compare "apple" and "banana" alphabetically

    "apple" comes before "banana", so a.compareTo(b) returns a negative value, making result > 0 false.
  3. Final Answer:

    a <= b -> Option B
  4. Quick Check:

    compareTo() negative means first string is less [OK]
Quick Trick: compareTo() negative means first string is alphabetically before second [OK]
Common Mistakes:
  • Assuming compareTo() returns boolean
  • Confusing positive and negative return values
  • Expecting 0 when strings differ

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes