Char comparison in JSF EL Expression

As in Java single qoutes delimit a char and double qoutes delimit a String, in xhtml EL expressions both of them are representing a String.

Let’s say we have a simple char property in our bean:

public char getY() {
  return 'Y';
}

If we try to compare the value of `Y` to a char

<h:outputText value="TRUE" rendered="#{indexView.y eq 'Y'}"/>

we will get an error message:

javax.el.ELException: Cannot convert [Y] of type [class java.lang.String] to [class java.lang.Long]

But what is Long doing here? If we take a look at the
Jakarta Expression Language Specification we can find that characters are coerced as a Long value, the Unicode value of the character.

1.23.4. Coerce A to Character or char
If A is String, return A.charAt(0)

Solution 1

First solution can be to convert the `String` value to a `Char`. The String.charAt() function can be useful here.

<h:outputText value="TRUE" rendered="#{indexView.y eq 'Y'.charAt(0)}"/>

Solution 2

As char values are internally coerced to long values we can use the Unicode value of our character to do the comparison:

<h:outputText value="TRUE" rendered="#{indexView.y eq 89}"/>

Solution 3

The first solution is just a workaround. The second solution can be a little pain because you have to search for the char’s Unicode value.

The best solution would be if you create a new enum representing the char you want to examine.

public enum YesNoUnknownEnum {
  Y, N, U
}

public YesNoUnknownEnum getYes() {
  return YesNoUnknownEnum.Y;
}

In this case you can compare your char value with your enum value:

<h:outputText value="TRUE" rendered="#{indexView.yes eq 'Y'}"/>

Epilogue

Char comparison seems to be a little pain in EL Expressions. You only have to remember single quotes are representing a `String` and can not be compared to a `Char`.