char comparison in EL expression [duplicate]
Asked Answered
L

2

6

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?

Lamarre answered 10/5, 2012 at 22:8 Comment(2)
Cannot reproduce on tomcat 7. Maybe you could show us the actual code that doesn't work?Quacksalver
I run it on Tomcat 7. Maybe you didn't add JSTL library to your projectVitek
S
8

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>
Stalky answered 11/5, 2012 at 4:59 Comment(1)
Thanks, it works that way :) I didn't know that '1' is String in this case.Vitek
P
7

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.

Pederson answered 11/5, 2012 at 7:27 Comment(1)
Thank you for your reply. '1' is as String, indeed. I was wrong thinking that it is a character, I have to read more specification :)Vitek

© 2022 - 2024 — McMap. All rights reserved.