Can you compare chars with ==? [duplicate]

℡╲_俬逩灬. 提交于 2019-11-28 07:44:07

问题


For Strings you have to use equals to compare them, because == only compares the references.

Does it give the expected result if I compare chars with == ?


I have seen similar questions on stackoverflow, E.g.

  • What is the difference between == vs equals() in Java?

However, I haven't seen one that asks about using == on chars.


回答1:


Yes, char is just like any other primitive type, you can just compare them by ==.

You can even compare char directly to numbers and use them in calculations eg:

public class Test {
    public static void main(String[] args) {
        System.out.println((int) 'a'); // cast char to int
        System.out.println('a' == 97); // char is automatically promoted to int
        System.out.println('a' + 1); // char is automatically promoted to int
        System.out.println((char) 98); // cast int to char
    }
}

will print:

97
true
98
b



回答2:


Yes, but also no.

Technically, == compares two ints. So in code like the following:

public static void main(String[] args) {
    char a = 'c';
    char b = 'd';
    if (a == b) {
        System.out.println("wtf?");
    }
}

Java is implicitly converting the line a == b into (int) a == (int) b.

The comparison will still "work", however.



来源:https://stackoverflow.com/questions/45893095/can-you-compare-chars-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!