Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

EL operator - not operator

 
roshni sivan
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai all,

I am preparing for SCWCD 5.0 and I could not understand the following code.

<%
java.util.Map map = new java.util.HashMap();
map.put("a","true");
map.put("b", "false");
map.put("c", "42");
%>

<h3>${not map.c}</h3>

If thought (not 42) will result in false. But the above code displays output as true. Please clarify me on this.

Thanks.

Roshni
 
Matteo Palmieri
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your question is very intersting and after a few investigation I found out how to solve it. Actually to answer the question correctly we have to understand how the Boolean.valueOf(String) method is supposed to work (this is covered in SCJP exam). This method returns false if the argument is null or anything different from true (the uppercase or lowercase makes no difference). As the argument of the EL not operator in your code has to be a boolean, a type coercion is performed. The map.c argument resolves to null, because map is actually a scripting variable, not corresponding to a scope variable. Thus the negation resolves to true.
[ December 08, 2008: Message edited by: Matteo Palmieri ]
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In simple terms.
EL treats unknown variables as 0 in arithematic expressions.
Hence ${xyz + 22} = 22
EL treats unknown variables as false in relational expressions.
Hence ${not xyz} = true.
EL converts strings to numbers if possible in arithematic expressions.
${"1"+"2"} = 3
But
${"aaa"+"aaa"} = javax.servlet.ServletException: An exception occured trying to convert String "aaa" to type "java.lang.Long"

In your case map is a scripting variable and not available to EL and hence
${ not map.c} ==> ${not unknown_variable} ==> ${not false} ==> true
 
roshni sivan
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic