简体   繁体   中英

Null Pointer Access Warning

A part of the code I made should have looked like this.

String name = request.getParameter("Name");
if(name!=null && !name.isEmpty())
{
    DO SOMETHING
}

But ended up using '||' operator rather than '&&' operator. And i was given a warning at

name .isEmpty()

saying

Null Pointer Access: The variable name can only be null at this location.

Can somebody explain me why that happened?

And by the way, ' request ' is a HttpServletRequest Object that i get from a previous class.

name != null || !name.isEmpty()
  1. If name is not null, the second condition is never checked;
  2. if name is null, the second condition is checked and throws a NullPointerException .

When you do:

if(name!=null || !name.isEmpty())

Then if the second part is reached, name is null due to Short-circuit evaluation .

Remember that false && anything is false and true || anything true || anything is true .

You can do:

String name = request.getParameter("Name") != null ? request.getParameter("Name") : "";

to ensure that name is not null . And then

if (name.isEmpty()) { ... }
if(name!=null ){
   if(!name.isEmpty()){
       //body
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM