0

Basically I have a if..else logic as below

if(request.getParameter("action")=="delete" && request.getParameter("action")!=null)  
{
   //delete operation
}
else
{
  //update operation
}

But during update process "action" parameter do not get attached with URL and hence NullPoitnerException is thrown.

Any solution to fix it? Thanks in advance!

Nisarg
  • 63
  • 1
  • 3
  • 8
  • 1
    Duplicate question [How to test if a variable is set?](http://stackoverflow.com/questions/7703622/how-to-test-if-a-variable-is-set) – Haridarshan Feb 04 '16 at 05:36
  • Interesting where do you get NullPoitnerException? Even if `getParameter("action")` will return `null` you can not get this exception in your `if-conditions`. – Radu Dumbrăveanu Feb 04 '16 at 09:02

2 Answers2

0

In Java 8 you can do like this

Optional<String> paramOptional=Optional.ofNullable(request.getParameter());
        paramOptional.ifPresent(param->{
            //Do something with param
        });
 OR
 String param =paramOptional.orElse("you else string");//if null then this string will be return
Noor Nawaz
  • 2,175
  • 27
  • 36
0

If your request.getParameter(x) returns null when x is not set, you could simply swap the two conditions in your if-clause.

Thus

if(request.getParameter("action")=="delete" && request.getParameter("action")!=null)

would become

if(request.getParameter("action")!=null && request.getParameter("action")=="delete")

Since && is a short-circuit Boolean And in Java, this will cause the the second half of the statement to be executed only if the part before the && evaluates to true - thereby preventing your NullPointerException.

request.getParameter("action")=="delete" is a comparison with a string literal, though. You are most likely better off using .equals() instead.

Community
  • 1
  • 1
morido
  • 1,027
  • 7
  • 24