• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

Declare variables in scriptlet?

 
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; %> ???
 
author
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.
 
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.
 
It sure was nice of your sister to lend us her car. Let's show our appreciation by sharing this tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic