Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing to string with each other in Java

Tags:

java

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.

like image 973
Ordo Avatar asked Nov 22 '25 09:11

Ordo


2 Answers

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.

like image 122
fastcodejava Avatar answered Nov 24 '25 23:11

fastcodejava


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 {
 ...
}
like image 20
Samuel Parsonage Avatar answered Nov 24 '25 22:11

Samuel Parsonage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!