Reputation: 9
I'm learning java now. I have a book which is up to SE6 date. Now there is an exercise that asks me:
Write a method that takes two String arguments and uses all boolean comparisons to compare the two Strings and print the results. In main(); call your method with some different String objects.
When I tried:
public static void compare(String a, String b){
System.out.println(a>b);
}
I got error said > operator is not valid for type String
Now my question is - if the book is out of date and something changed since, or am I misunderstanding something in the task?
Upvotes: 0
Views: 192
Reputation: 11
You cannot use relational operators( <, <=, >,>=) on Strings in Java. Java does not rely on operator overloading.
You can use compareTo method for comparing Strings: The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.
Upvotes: 0
Reputation: 298
I guess this task was meant for you to provide your own implementation of string comparison, so for example:
for (int i = 0; i < Math.max(a.length(), b.lentgh(); i++) {
if (a[i] < b[i]) {
System.out.println("a < b");
return;
}
// ...
Strings are objects, not primitives, and cannot be compared with comparison operators. There is a compareTo(String anotherString) method build into String which returns a number depending on which string is lexically greater.
Upvotes: 1