[java] Comparing chars in Java

I want to check a char variable is one of 21 specific chars, what is the shortest way I can do this?

For example:

if(symbol == ('A'|'B'|'C')){}

Doesn't seem to be working. Do I need to write it like:

if(symbol == 'A' || symbol == 'B' etc.)

This question is related to java comparison char

The answer is


You can just write your chars as Strings and use the equals method.

For Example:

String firstChar = "A";
String secondChar = "B";
String thirdChar = "C";

if (firstChar.equalsIgnoreCase(secondChar) ||
        (firstChar.equalsIgnoreCase(thirdChar))) // As many equals as you want
{
    System.out.println(firstChar + " is the same as " + secondChar);
} else {
    System.out.println(firstChar + " is different than " + secondChar);
}

If you have specific chars should be:

Collection<Character> specificChars = Arrays.asList('A', 'D', 'E');  // more chars
char symbol = 'Y';
System.out.println(specificChars.contains(symbol));   // false
symbol = 'A';
System.out.println(specificChars.contains(symbol));   // true           

pseudocode as I haven't got a java sdk on me:

Char candidates = new Char[] { 'A', 'B', ... 'G' };

foreach(Char c in candidates)
{
    if (symbol == c) { return true; }
}
return false;

you can use this:

if ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(String.valueOf(yourChar)))

note that you do not need to create a separate String with the letters A-Z.


If you know all your 21 characters in advance you can write them all as one String and then check it like this:

char wanted = 'x';
String candidates = "abcdefghij...";
boolean hit = candidates.indexOf(wanted) >= 0;

I think this is the shortest way.


Yes, you need to write it like your second line. Java doesn't have the python style syntactic sugar of your first line.

Alternatively you could put your valid values into an array and check for the existence of symbol in the array.


One way to do it using a List<Character> constructed using overloaded convenience factory methods in is as :

if(List.of('A','B','C','D','E').contains(symbol) {
    // do something
}

The first statement you have is probably not what you want... 'A'|'B'|'C' is actually doing bitwise operation :)

Your second statement is correct, but you will have 21 ORs.

If the 21 characters are "consecutive" the above solutions is fine.

If not you can pre-compute a hash set of valid characters and do something like

if (validCharHashSet.contains(symbol))...

Using Guava:

if (CharMatcher.anyOf("ABC...").matches(symbol)) { ... }

Or if many of those characters are a range, such as "A" to "U" but some aren't:

CharMatcher.inRange('A', 'U').or(CharMatcher.anyOf("1379"))

You can also declare this as a static final field so the matcher doesn't have to be created each time.

private static final CharMatcher MATCHER = CharMatcher.anyOf("ABC...");

Option 2 will work. You could also use a Set<Character> or

char[] myCharSet = new char[] {'A', 'B', 'C', ...};
Arrays.sort(myCharSet);
if (Arrays.binarySearch(myCharSet, symbol) >= 0) { ... }

It might be clearer written as a switch statement with fall through e.g.

switch (symbol){
    case 'A':
    case 'B':
      // Do stuff
      break;
     default:
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to comparison

Wildcard string comparison in Javascript How to compare two JSON objects with the same elements in a different order equal? Comparing strings, c++ Char Comparison in C bash string compare to multiple correct values Comparing two hashmaps for equal values and same key sets? Comparing boxed Long values 127 and 128 Compare two files report difference in python How do I fix this "TypeError: 'str' object is not callable" error? Compare cell contents against string in Excel

Examples related to char

How can I convert a char to int in Java? C# - How to convert string to char? How to take character input in java Char Comparison in C Convert Char to String in C cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)' How to get the real and total length of char * (char array)? Why is conversion from string constant to 'char*' valid in C but invalid in C++ char *array and char array[] C++ - How to append a char to char*?