• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock Exam question.

 
Rohit Kelkar
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If no parameter is supplied what is the output of:
<%String s=request.getParameter("param");
out.println(s);%>
You answered: A

A NullpointerException occurs
B Page compiles but there is no output
C ServletException occurs
D null is printed on screen
D is correct null is printed and the page compiles fine.
I check it and the ans is D. But I was wondering why don't I get a nullpointer exception.
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rohit
A NullPointerException is when you try to access a variable that does not refer to an existing object.
In the case here though you're not refering to any objects you are simply calling a method on the request object that returns a value. In this case the request object exists it is the parameter that doesn't exist. Now, if the request object did not exist you'd get the NullPointerException.
hope that helps
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method returns null, which basically gives you:
String s = null ;
As in any Java code, if you try to print a String that contains a null reference, the output is "null" (minus the "'s of course).
Now why did they make getParameter return a null value instead of throwing a NullPointerException? The specification doesn't appear to make mention of why null is returned (that I can find at least), but I assume it is to put the responsibility on the developer for handling at runtime what happens if the attribute doesn't exist.
Throwing an exception involves introducing new references and all that when it isn't really practical or necessary to do so. Why create a whole new exception object for you to handle when you can just return a null and let the developer deal with it as they will? Takes less resources from a container standpoint.
If you really want to know what's happening behind the curtain, find the container's implementation of HttpServletRequest and look at getParameter(), see how they're handling things.
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or what Dave said, which makes a whole heck of a lot more sense, in a lot fewer words...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic