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

SCWCD Question

 
Al Tam
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I found a site with some good SCWCD 1.4 mock questions. However, as I'm just a novice at the SCWCD, I didn't quite understand the answer to one of the questions.

Here is the link:

http://www.certgear.com/products/preview/scwcd/index.html

I don't quite understand the answer to the first question:

What will be the output of the following JSP code?

<html><body>
<% int a = 10; %>
<%! int a = 20; %>
<%! int b = 30; %>
The value of b multiplied by a is <%= b * a %>
</body> </html>

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 wouldn't the compiler complain of declaring the variable "a" twice in the JSP code?
 
harikumar devandla
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NO!! It will not give a compile time error.
The variable "a" is declared twice but 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 JSP engine will translate the 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.
 
Dale Seng
Ranch Hand
Posts: 275
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it's got "<%!" that means it's a declaration (outside of the service method). So the "a" without the "<%!" wins.

--Dale--
 
harikumar devandla
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yep!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic