rozi rozi - 28 days ago 5
Java Question

Why am I getting NullPointerException in a logic expression

I am trying to build a basic MVC design pattern with servlets and jsp.So what i an doing is passing username and password from my jsp page then I am redirecting it to a validator class called LoginService which is basic validation like if username and password is null then the returned value is false.

For that I have implemented code as:

package businessservice;

public class LoginService {


public boolean authenciate(String userId , String password)
{
if(userId!=null && userId.trim()!=null)
{
if (password!=null && password.trim()!=null)
{
return true;
}
else
{
return false;
}
}

else{
return false;
}
}
}


Here I get
NullpointerException
at lines
if(userId!=null && userId.trim()!=null)
and
if (password!=null && password.trim()!=null)
.

The error is as:


SEVERE: Servlet.service() for servlet [mvcservlet.LoginServlet] in context with path [/MVCLoginApp] threw exception
java.lang.NullPointerException at businessservice.LoginService.authenciate(LoginService.java:10)


But if I turn the function other way round i.e.

package businessservice;

public class LoginService {


public boolean authenciate(String userId , String password)
{
if(userId==null | userId.trim()=="")
{
if (password==null | password.trim()=="")
{
return false;
}
}

return true;
}
}


I think It works as expected.But I am unable to figure out why the first one creates null pointer exception.It will be a great help if anyone can help me understand it.

Thanks in advance!

I have got the answer that solved my problem:
I was using == which was not relevant for the case as I have to compare contents of strings.Which you can see more at

How do I compare strings in Java?

The answer that solved my problem was of Joop Eggen Sir which is below in the answer section.

Answer

First:

if(userId!=null && userId.trim()!=null)

should be

if (userId != null && !userId.trim().isEmpty())

and

if(userId==null | userId.trim()=="")

should be

if (userId==null || userId.trim().isEmpty())

What should have worked:

public boolean authenciate(String userId, String password) {
    return userId != null && !userId.trim().isEmpty()
            && password != null && !password.trim().isEmpty();
}

This does not explain your NullPointerException as in the first case everything was guarded.

The sole reason might be that the LoginService instance was null. As | does evaluate both sides, a second error might have hidden the first. Also mind that == does not compare string values; for that use equals.

Maybe this is not the exact code, and in the original code there was a field userID and a typo userID. - My guess.

Comments