File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Question to an output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Question to an output" Watch "Question to an output" New topic
Author

Question to an output

Urs Waefler
Ranch Hand

Joined: Mar 13, 2007
Posts: 77
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?


SCJP 1.4
Venkata Kumar
Ranch Hand

Joined: Apr 16, 2008
Posts: 110

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.


SCJP 5.0, SCWCD 5, preparing for SCDJWS
Chinmaya Chowdary
Ranch Hand

Joined: Apr 21, 2008
Posts: 432
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'.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question to an output