this qn is from enthuwhere sample mock i am little bit confused with the answer given them what will be the answer for this qn?
Consider the following JSP code (See exhibit).
What will it print for the very first request to this page as well as the web application that contains this page?
Select 1 correct option.
1) It will print Hello!
2) It will print Hello and will set the count attribute in the session.
3) It will throw a NullPointerException at request time.
4) It will not compile.
the answer given is option 2
The code could be like
<% Integer count = (Integer) request.getSession(false).getAttribute("count");
if(count != null )
request.getSession(true).setAttribute("count", new Integer(1));%>
the option 2 is correct.
The explanation is as follows:
1. It is a JSP file
2. If there is no <%@ page session="false" %> explicitly, then session is set to true by default. It means, that the session object is created before the very first line of the JSP page (in the jsp's servlet class definition).
1. there already is a session existing since request.getSession(false) doesn't create a session if there isn't one already ?
2. ok, assuming there is a session already, the value of getAttribute would be null becuase otherwise, it would come to the out.println statement. But its going to the setting the attribute else.
But aren't we typecasting a null value to an Integer. How is that not throwing an exception ?
Hopefully, I have made my doubts clear...Could someone help us out ? Thanks.
WRT the NullPointerException, if you're talking about the following statement...
... that's an assignment, not a downcast.
Ritu, casts are allowed from null to any class, interface, or array type. Basically, the verifier checks if myInt can be assigned 'null'. Sure, all objects can. Hence there is no ClassCastException.