Can compareTo Handle All String Comparisons in Java?

  • Context: Java 
  • Thread starter Thread starter tbrown427
  • Start date Start date
  • Tags Tags
    Java
Click For Summary
SUMMARY

The Java code provided in the discussion demonstrates a common mistake when using the compareTo method for string comparisons. The if-else statement does not correctly utilize the result of the compareTo method, leading to the same output regardless of the comparison. The correct implementation should differentiate the output based on the comparison result. This highlights the importance of properly handling conditional statements in Java.

PREREQUISITES
  • Understanding of Java programming language
  • Familiarity with String class methods in Java
  • Knowledge of conditional statements in Java
  • Basic debugging skills in Java
NEXT STEPS
  • Review Java String compareTo method documentation
  • Practice writing conditional statements in Java
  • Explore debugging techniques for Java applications
  • Learn about Java String manipulation methods
USEFUL FOR

Java developers, programming students, and anyone looking to improve their understanding of string comparisons and conditional logic in Java.

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.
 

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