• Post Reply Bookmark Topic Watch Topic
  • New Topic

Variables in JSP  RSS feed

 
Anand Gondhiya
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in C/C++ you can do following :
int a=0; // global variables
void func()
{
int b = 5;
a = b; // after this a's value is 5.
}
how do you write the same function in JSP so that a's value gets changed to 5.
here is the sample code :
<%! int a = 0 %>
<%! void func()
{
int b = 5;
a = b; // after this a's value is 5.
}
%>
<%-- following statement gives a's value 0 %>
<% func();
out.println(" a "+ a);
%>
How do u do it ?
Thanks in advance
 
Kishore Dandu
Ranch Hand
Posts: 1934
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well to my knowledge, JSP follows the same programming rules as Java.
Since the variable a is defined outside the scope of function, it gets value of 5 only inside the function(since the variable is only passed by value and you are reinitializing it to 0 inside the function). If the reinitialization occurs outside a function it should get value of 5.
Rememer that all your code inside <%.... %> is processed on the server side.
Dan.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65833
134
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anand, firstly your example will not even compile. If you are going to ask people to spend time helping you, please take the time to make sure your questions are clear and any code samples are accurate.

Since the variable a is defined outside the scope of function, it gets value of 5 only inside the function

That make no sense. a is defined outside the method and there's no concept that a global variable will have a special "method internal" value. That might be true of passed parameters, but not of global variables.
When I added the missing semicolon to the end of the first declaration, I ran your example and got the expected output of "a 5".
Here's my complete test:

[ March 08, 2004: Message edited by: Bear Bibeault ]
 
Kishore Dandu
Ranch Hand
Posts: 1934
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
my bad, my bad on the global stuff.
Dan.
 
Anand Gondhiya
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help Bear. I will extra careful from now onwards about my code samples.
Thanks to to you Chris.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!