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?
Yes, char is just like any other primitive type, you can just compare them by == .
To compare two char values, use the == operator x == y .
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With