Forums Register Login

Declare variables in scriptlet?

+Pie Number of slices to send: Send
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; %> ???
+Pie Number of slices to send: Send
Yes, they do. The code as shown by you above is certainly valid.
- Peter
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
 

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.
My honeysuckle is blooming this year! Now to fertilize this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1411 times.
Similar Threads
int []i,j[]==int i[], j[][] ???????
Question on JSP
Difference between %! and % when declaring variables in .jsp
Question Bank ID 41-- JSP to Servlet Conversion Rule
jspInit() method
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 05:00:18.