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?
Related Topics
Lazarus: Program without GUI - Many WSRegister Errors
Question | 6 Answers
Java: Case Insensitive Equals - String Comparison
Info | 0 Comments
Java: How to compare Strings correctly
Question | 1 Answer
O-Notation
Article | 0 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
PHP: Only MOD-Operator? How to do DIV in PHP?
Question | 2 Answers
Android Programming: Receive Responce from HTTP POST Request
Tutorial | 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.
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:
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():
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