24 Votes

Java: Smaller/Larger Comparison of Strings - The operator > is undefined for the argument type(s) java.lang.String

Question by Guest | 2013-09-30 at 18:38

I would like to implement a string comparison with Java. For example, when comparing the strings "a" and "b", "a" is smaller than "b", "b" is greater than "a" and "a" is equal to "a" or "b" is equal to "b".

So far so good. In other programming languages, it was not a great deal to code such a comparison, but Java complains when using ">" and "<" and also "==" does not work:

String a = "a";
String b = "b";

if (a > b) { ... }
if (a < b) { ... }
if (a == b) { ... }

No matter how I rewrite this code, I always get the following error message:

The operator > is undefined for the argument type(s) java.lang.String,
java.lang.String

So, what can I do so that I can compare a string with another string?

ReplyPositiveNegative
2Best Answer2 Votes

In Java, you can not simply compare strings in the way you did, because in Java strings are individual objects.

Instead, use the method compareTo() for the larger-smaller comparison:

String a = "a";
String b = "b";

if (a.compareTo(b) < 0)  { } // true
if (a.compareTo(b) > 0)  { } // false
if (a.compareTo(b) == 0) { } // false

The result of .compareTo() is smaller than 0 in the case "a" is smaller than "b", greater than 0 when "a" is greater than "b" and equal to 0, if "a" and "b" contain the same characters.

If you're only interested in whether "a" and "b" have the same content, you can also use .equals():

String a = "a"
String b = "b";

if (a.equals(b)) { }  // true

Depending on the content of "a" and "b", .equals() returns true or false. More about this, you can read in the question about Java string comparison. There, this comparison is explained in more detail.
2013-10-01 at 18:55

ReplyPositive Negative
Reply

Related Topics

O-Notation

Article | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.