Can you compare chars with ==?
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
Yes, but also no.
Technically, ==
compares two int
s. 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.