October 10, 2012

What will be the output of the following JSP code ?

Jsp Code:



<! int a =20>
<! int b = 30>
<%= b* a>




May be bellow answers suitable(chose any one):
(A) The code will not compile
(B) The value of b multiplied by a is 30
(C) The value of b multiplied by a is 300
(D) The value of b multiplied by a is 600
(E) The value of b multiplied by a is 0

Why The is the correct answer(s):
(C) The value of b multiplied by a is 300

Explanation:
Although the variable "a" is declared twice, the code should still compile as written. In the first declaration
 <% int a = 10; %>, the variable "a" will be declared as a local variable. In the second declaration 
<%! int a = 20; %>, the variable "a" will be declared as an instance variable, global to the translated servlet class.
Upon translation, the Container will translate the JSP code similar to the following:
public class ..._jsp
{
int a = 20;
int b = 30;
public void _jspService (....)
{
int a = 10;
out.write ("The value of b multiplied by a is ");
out.print (b * a);
}
Since the local variable "a" has precedence over the global variable "a", 
the expression (b * a) evaluates as (30 *10), which equals 300.

Reference: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPIntro7.html

1 comment:

  1. Please make the question clear. There is no reference to the local variable 'a' .

    ReplyDelete

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts