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

Declare variables in scriptlet?

 
Marshall B Thompson
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I took a mock exam recently that had something like:
<% int i; %>
<% ...manipulate i... %>
Exam said would fail to translate cause declarations must be inside <%! %>.
Don't scriptlets just get inserted into _jspService? So, couldn't you declare a variable local to _jspService via <% int i; %> ???
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, they do. The code as shown by you above is certainly valid.
- Peter
 
Marshall B Thompson
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's the scoop - Whizlabs had a sample question and explanation along these lines.
<%! int x; %>
<%! int x = 0; %>
<% int x = 0; %>
are all valid.
<% int x; %> is NOT. Reason being, scriptlets are inserted into _jspService. So any variables declared in a scriptlet are local to _jspService. Declaration of local variables REQUIRES initialization. Thus <% int x=0; %> is valid while <% int x; %> is not.
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Marshall B Thompson:
<% int x; %> is NOT.

Hum, Yes and No, It depends on the rest of the code. JPS follow the same rules for local variables that other Java Classes follow (After all, this does make it into the Java Class created for your JSP inside the _jspService method)
If you do the initalization later in a decision block and access it afterwards, you'll get the "i may not have been initalized exception. If your code is setup so the next thing that has to happen with i is that it gets initialized, it's cool such as:

Would be allowed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic