• Post Reply Bookmark Topic Watch Topic
  • New Topic

EL Query Arithmatic Operator

 
Ashu Jain
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a query - Deshmukh book says that Strings canbe used in airthmetic operators as long as they can be converted into numbers.

Eg - ${"16" % 4} evaluated to 65
${a div 4} evaluates to 0.0
${"a" div 4} produces a compilation error

Q1 - How ${a div 4} evaluates to 0.0. Is "a" ASCII values used ?
Q2 - If ${a div 4} can be evaluated why cant ${"a" div 4}. Aren't they same thing.

 
Charles Lyons
Author
Ranch Hand
Posts: 836
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here, the letter 'a' is an EL variable (an object in one of the scopes page/request/session/application). I assume the variable isn't actually declared in one of the scopes, so when EL does ${a div 4} it is attempting to divide the variable 'a' which doesn't exist by 4. This is defined (through a number of coercion rules) to produce 0.

But in the case of "a", it is a string which cannot be converted to a number at all. However, this doesn't result in a compilation error. It cannot because EL expressions aren't parsed by the JSP compiler (well it isn't guaranteed; there might at some point be a parser which does cope with EL, but the existing ones don't). It will however throw a runtime exception.

The official coercion rules read (in brief):So by these rules, the number 4 is converted to a Double in the obvious way. Then in your first case, the variable 'a' is null (since it isn't defined in a scope), so is evaluated to 0. Then 0/4 = 0. Good.

In the second case, the rules fail because Double.valueOf("a") throws a runtime exception.
[ December 21, 2008: Message edited by: Charles Lyons ]
 
Ashu Jain
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just a quick query - I thought a pair of single quotes is equal to pair of double quotes.

Isn't ${'a' div 4} similar to ${"a" div 4}. Assuming 'a' does not exist in any of the scopes. Should'nt both return zero ( null in EL ==> 0 and 0/4 is 0 )

Please clarify. Isn't single quotes considered same to double quotes.
 
Charles Lyons
Author
Ranch Hand
Posts: 836
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not try the example in your Web container and find out? It shouldn't take more than a minute or two...
 
Ashu Jain
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
u were right. Thanks. Seems like "a" is interpreted as String literal rather than an attribute in any one of four scopes.

Thanks
 
And then we all jump out and yell "surprise! we got you this tiny ad!"
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!