• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question to an output

 
Urs Waefler
Ranch Hand
Posts: 77
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I work with the book Sun Certified Web Component Developer (SCWCD) from David Bridgewater. I am in chapter 6, at the end one finds this question:

<%@ page language="java" %>
<html>
<head><title>Chapter 6 Question 2</title></head>
<body>
<h1>Chapter 6 Question 2</h1>
<%! int x = 0; %>
<%!
public void jspInit() {
System.out.println(x++);
}
%>
<%= x++ %>
<% System.out.println(x); %>
<% jspInit(); %>
</body></html>


The answer in the book is: 3. This seems to be the output to the web page on the second access. But I doubt, I do not understand it properly.

I understand these steps (first access):
i) x = 0 (initialization)
ii) x = 1 (this in System.out.println(x++))
iii) x = 2 (this is x++)
iv) x = 3 (this is jspInit() again)

Then second access follows:

There is no jspInit(). Although there is one x++. So, x = 4. Maybe first it prints 3, then it augments x. What is about the initialization x = 0?
 
Venkata Kumar
Ranch Hand
Posts: 110
Firefox Browser Java MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
variables delcared using %! %> are not local to service method. They will be class variables.So x is initialized only once when the instance of servlet is created. Separate thread is created for each request and all requests share the same variable x.
 
Chinmaya Chowdary
Ranch Hand
Posts: 432
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Urs. During initialization, the container calls the init() method and it calls jspInit(), here it prints 'x' value to '0' and increments it to '1'(since it is post increment). In 'x' value becomes '1', and increments it becomes '2'. Now the 'x' value is '2' and the container calls the and outputs '2'. After that it calls jspInit(), it prints '2' and incremets and 'x' becomes 3.

In second request, container calls service() method only. In _jspService() method, the jsp expression value is '3' and incremets 'x' and it becomes '4'. After that it calls System.out.println(x) and prints '4'. And calls jspInit() method( its like calling inline method) and prints 4 and increments 'x' and it becomes '5'.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic