I'm looking for a solution to compare two strings with each other. I have already found a few suggestions but i'm not really understanding how to do it. I want to do something like that:
String a = 23;
String b = 2;
if (a < b)
System.out.println("...");
else ..
I've found the compareTo method but i don't get the idea behind it. The code would be something like:
String a = 23;
String b = 2;
if (a.compareTo(b) < 0)
System.out.println("...");
else ..
But why should i compare to strings with each other and then compare it to zero?? I'm really confused.
You cannot do a < b in java with String. You have to use compareTo or Comparator.
You cannot write String a = 23; also. You can convert them to integer and then do a < b.
Read the API for compareTo
a.compareTo(b)
The result of this method call:
is a negative number (hence < 0) if a precedes b alphabetically (e.g. a="apple", b="bananna")
is 0 if it is the same string
and is a positive number if a is after b alphabetically
If you want to compare numeric values, either do your comparison on Integers or first parse the strings e.g.
if (Integer.parseInt(a) < Integer.parseInt(b)){
...
} else {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With