15

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.

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

Chris Snow
  • 23,813
  • 35
  • 144
  • 309
abinmorth
  • 527
  • 2
  • 8
  • 25
  • 8
    `char`s are primitives, so **yes**. – Elliott Frisch Aug 26 '17 at 07:37
  • 2
    Why don't you try this in your IDE? – Tim Biegeleisen Aug 26 '17 at 07:38
  • 5
    @TimBiegeleisen Not really reliable. If this were Strings, someone might try `String a = "Hello"; String b = "Hello"; if (a == b ) { System.out.println("Equal");}` and conclude that it's OK to compare Strings with `==`. – Dawood ibn Kareem Aug 26 '17 at 07:44
  • @DawoodibnKareem Good point, I didn't think of the String part of this. – Tim Biegeleisen Aug 26 '17 at 07:45
  • 1
    If not using `==`, how would you do it? A `char` is not an object, so you can use `equals()` like you do for strings. If you simply tried that, you'd know immediately, because it won't compile. A little research, and a bit of logical thinking, and you'd answer your own question. Both are necessary skills if you want to program, so you should start honing those skills now. – Andreas Aug 26 '17 at 08:45

2 Answers2

19

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
Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
4

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.

iono
  • 2,575
  • 1
  • 28
  • 36
Pod
  • 3,938
  • 2
  • 37
  • 45