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.
Read the API for compareTo
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.