Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char comparison in EL expression [duplicate]

I want to do something like this:

<c:if test="${somestring.charAt(0)=='1'}">
tadaaaam
</c:if>

when somestring is "11011" but it doesn't work. I can print it with

${somestring.charAt(0)}

and it is '1' but comparison above fails. The following comparison:

if(somestring.charAt(0)=='1')

worx (condition is true) in pure Java.

Any ideas?

like image 418
Dominik Kamiński Avatar asked May 10 '12 22:05

Dominik Kamiński


People also ask

Can you use == to compare chars?

Yes, char is just like any other primitive type, you can just compare them by == .

Can you compare two chars?

To compare two char values, use the == operator x == y .

How do I compare chars to other characters?

The syntax of compare() method is given as: compare(char x, char y); If both chars “x” and “y” are the same, the compare() method will return “0”. If the first char is less than the second char, it will return a negative value.


2 Answers

EL seems to have trouble with char. Here is the only way I could make it work.

<c:if test="${somestring.charAt(0)  == '1'.charAt(0)}" >
     tadaaaam
</c:if>
like image 53
rickz Avatar answered Nov 04 '22 13:11

rickz


The behaviour is exactly as expected and as required by the EL specification. If you take version 2.2 of the EL specification, you need to look at section 1.8.2 which provides the rules for the '==' operator.

The operands in this case are somestring.charAt(0) which is a char and '1' which is a String (NOT a char) since Strings may be delimited by either single or double quotes in EL.

Given we have Character == String, then the sixth bullet of 1.8.2 applies and both are coerced to Long values. The character will be coerced to 49 (the ASCII code for 1) and 1 is coerced to 1. These aren't equal hence the result you see.

I appreciate that this isn't what you would expect but it is the behaviour that is required by the specification and is triggered by the fact that single quotes in EL delimit Strings not chars.

like image 40
Mark Thomas Avatar answered Nov 04 '22 12:11

Mark Thomas