Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java.lang.NullPointerException

 
kevin schmidt
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My page is throwing the exception
"java.lang.NullPointerException". Now I was wondering, what am I doing for it to throw this. Here is a bit of the code:
try{
...
if(request.getParameter("sort").equals("Date")) {
...
}
else if (request.getParameter("sort").equals("Date")) {
...
}
else {
...
}
}
catch(Exception e) {
out.println("<tr><td>Exception: " + e + "</td></tr>");
}
The initial if statement works, the else if works, but when the page has to resort to the else statement, then I get the java.lang.NullPointerException error. What can I do? TIA.
Kevin
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if there is no such parameter as "sort", then the very first if statement will throw the nullpointerException.
http://www.javaranch.com/ubb/Forum7/HTML/005848.html http://www.javaranch.com/ubb/Forum7/HTML/005886.html

And that's only the ones that I've replied to.
 
Brian Blesbok
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
have a look at what you have posted here.
You are expecting us to try to tell you why you are getting an NPE in a section of code that you havent even given us.
First of all, the first statement will give an NPE if sort does not exist on the request, second, the 2nd statement is the *same* as the first.
Post the whole code if you want help
cheers
[This message has been edited by Brian Blesbok (edited September 14, 2001).]
 
BJ Grau
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Im with Mike on this. Without seeing the rest of your code I can guess that you are not checking if sort even exists before you are trying to call the equals method on it. If sort does not exist in the request, request.getParameter("sort") will return null and then you are trying to call equals on null which will throw a NullPointerException. NullPointerException was specifically made by the folks at Sun to tell us when we are trying to call a method on null.
Good luck.
[This message has been edited by BJ Grau (edited September 15, 2001).]
 
Dave Soto
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general, you should have a little construct like this whenever you get a parameter.
String myParameter = request.getParameter("myParameter");
if (myParameter != null)
//write your code, make your comparison, whatever you like
else
//handle your error (the fact that myParameter is null)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic