你能用==比较字符吗?
Can you compare chars with ==?
对于字符串,您必须使用等于来比较它们,因为 == 只比较引用。
如果我将字符与 == 进行比较,是否会给出预期的结果?
我在Whosebug上看到过类似的问题,例如
- What is the difference between == vs equals() in Java?
但是,我还没有看到有人询问关于在字符上使用 ==。
是的,char
就像任何其他原始类型一样,您可以通过 ==
来比较它们。
您甚至可以将 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
}
}
将打印:
97
true
98
b
是的,但也不是。
从技术上讲,==
比较两个 int
。所以在如下代码中:
public static void main(String[] args) {
char a = 'c';
char b = 'd';
if (a == b) {
System.out.println("wtf?");
}
}
Java 将行 a == b
隐式转换为 (int) a == (int) b
.
比较仍然 "work",但是。
对于字符串,您必须使用等于来比较它们,因为 == 只比较引用。
如果我将字符与 == 进行比较,是否会给出预期的结果?
我在Whosebug上看到过类似的问题,例如
- What is the difference between == vs equals() in Java?
但是,我还没有看到有人询问关于在字符上使用 ==。
是的,char
就像任何其他原始类型一样,您可以通过 ==
来比较它们。
您甚至可以将 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
}
}
将打印:
97
true
98
b
是的,但也不是。
从技术上讲,==
比较两个 int
。所以在如下代码中:
public static void main(String[] args) {
char a = 'c';
char b = 'd';
if (a == b) {
System.out.println("wtf?");
}
}
Java 将行 a == b
隐式转换为 (int) a == (int) b
.
比较仍然 "work",但是。