简体   繁体   中英

why cant we use <, <=, >,>= relational operators on String?

I want to know why we cant use the < , <= , > or >= relational operators on Strings.

import java.util.*;
public class Coffee{
    public static void main(String args[]){
        String s1="Cat";
        String s2="Dog";
        System.out.println(s1 < s2);
    }
}

gives the error "operator < cannot be applied to java.lang.String".

Why can't Java compare strings like this: C < D ?

The simple answer is: because they weren't implemented. Java (unlike eg C/C++) does not rely on operator overloading, so you have to get the value of a String with length method and then compare the results with your < > <= >= operators.

Side note: Strings in Java also implement Comparable interface. It allows you to use compareTo method, which returns 0 if the argument is a strings are equal, a value less than 0 if the argument is greater than string which you run this method on; and a value greater than 0 if the argument is a string smaller than this string.

Side note 2: By "greater string" I mean lexicographically greater (alphabetically).

String is not a primitive data type like int and double are. Strings are objects.

For Strings, the relational operator, ==, only checks to see if the objects "point" to the same data in the heap.

For example,

String s1="Cat";
String s2= new String("Cat");

if(s1==s2)
System.out.println("They are the same");

The if statement WILL NOT execute. This is because after you created an instance of "Cat", you create another instance of "Cat," in the heap. The two variables do not "point" to the same data.

compareTo methods check to see if the actual data that the variables are allocated to in a heap are equal to each other, and is one of the many correct ways to see if two String objects are equal to each other.

I hope it helped, if my response is unclear, please do not hesitate to ask.

If you really want to do this, use the compareTo result.

if ("a".compareTo("b") >= 0) {
    // do stuff
}

If you want to ignore case you can do:

if (String.CASE_INSENSITIVE_ORDER.compare("A", "b") <= 0) {
   // do stuff
}

Here's the right way:

import java.util.*;
public class Coffee {
    public static void main(String args[]) {
        String s1="Cat";
        String s2="Dog";
        System.out.println(s1.compareTo(s2));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM