Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you compare chars with ==? [duplicate]

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.

like image 947
abinmorth Avatar asked Aug 26 '17 07:08

abinmorth


People also ask

Can you compare chars with == in Java?

Using ==, <, > operators you should be able to compare two characters just like you compare two integers. Note: Comparing char primitive values using < , > or == operators returns a boolean value.

How do you compare chars in C ++?

strcmp() in C/C++ This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.

How can you tell if two characters are equal?

The equals() method is used to check whether two char objects are equal or not. It returns true if both are equal else returns false .


2 Answers

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.

like image 160
Pod Avatar answered Oct 29 '22 04:10

Pod


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
like image 18
Krzysztof Cichocki Avatar answered Oct 29 '22 02:10

Krzysztof Cichocki