• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

Question to an output  RSS feed

Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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" %>
<head><title>Chapter 6 Question 2</title></head>
<h1>Chapter 6 Question 2</h1>
<%! int x = 0; %>
public void jspInit() {
<%= x++ %>
<% System.out.println(x); %>
<% jspInit(); %>

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?
Ranch Hand
Posts: 110
Firefox Browser Java MySQL Database
  • 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.
Ranch Hand
Posts: 437
Java Oracle
  • 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'.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!