Java Can compareTo Handle All String Comparisons in Java?

  • Thread starter Thread starter tbrown427
  • Start date Start date
  • Tags Tags
    Java
Click For Summary
The Java code provided is intended to compare two strings, "rabbits" and "capes," using the compareTo method. However, the output is consistently "capes rabbits" regardless of the comparison result. This occurs because both the if and else branches contain the same print statement, leading to no variation in output. To achieve the intended functionality, the code should differentiate the outputs based on the comparison result, ensuring that different messages are printed for each condition. The current structure fails to utilize the comparison effectively, resulting in a lack of meaningful output.
tbrown427
Messages
1
Reaction score
0
I can't get this to test all the way through

Code:
import java.util.Scanner;

public class OrderStrings {
   public static void main (String [] args) {
      String firstString;
      String secondString;

      firstString  = "rabbits";
      secondString = "capes";

     if (secondString.compareTo(firstString) >0){
         System.out.println("capes rabbits");
     }
     else {
         System.out.println("capes rabbits");
     }
      return;
   }
}
 
Technology news on Phys.org
This code compiles and executes, but the output is always
capes rabbits

Look at your if else statement and notice it makes no difference the result of compareTo; it always just prints the above.
 
Anthropic announced that an inflection point has been reached where the LLM tools are good enough to help or hinder cybersecurity folks. In the most recent case in September 2025, state hackers used Claude in Agentic mode to break into 30+ high-profile companies, of which 17 or so were actually breached before Anthropic shut it down. They mentioned that Clause hallucinated and told the hackers it was more successful than it was...

Similar threads

  • · Replies 12 ·
Replies
12
Views
15K
Replies
8
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 2 ·
Replies
2
Views
13K