Java 你能用 == 比较字符吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45893095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:13:15  来源:igfitidea点击:

Can you compare chars with ==?

javacharcompareequals

提问by abinmorth

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

对于字符串,您必须使用 equals 来比较它们,因为 == 只比较引用。

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

如果我将字符与 == 进行比较,它会给出预期的结果吗?



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

我在stackoverflow上看到过类似的问题,例如

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

但是,我还没有看到询问在字符上使用 == 的问题。

采纳答案by Krzysztof Cichocki

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

是的,char就像任何其他原始类型一样,您可以通过==.

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

您甚至可以将 char 直接与数字进行比较并在计算中使用它们,例如:

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

回答by Pod

Yes, but also no.

是的,但也不是。

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

从技术上讲,==比较两个ints。所以在如下代码中:

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 == binto (int) a == (int) b.

Java 正在隐式地将行a == b转换为(int) a == (int) b.

The comparison will still "work", however.

然而,这种比较仍然“有效”。