简体   繁体   中英

Conditional statement for null check

i have one conditional statement as below

if (Sizeval != null) {
            query.addFilterQuery("size:" + Sizeval);
        }

In debug i can see value of Sizeval = null

I am getting this value from a request object as below

Sizeval = (String) request.getParameter("Attr");

But even though Sizeval is null its executing the query.addFilterQuery statment.

Any suggestion to rectify this issue plz

To rephrase your question. Given

HttpServletRequest requst = ...
String Sizeval = (String) request.getParameter("Attr");
if (Sizeval != null) {
    query.addFilterQuery("size:" + Sizeval);
}

you see that the body of the if is executed (implies Sizeval not null) but still Sizeval seems to be null (as observed in the debugger or in the constructed filter).

Explanation: Sizeval is not null but has the literal value "null" . This will add a "size:null" filter query. Also when the variable is viewed in a log or debugger it will seem to be null .

To verify do

if (Sizeval != null) {
    if ("null".equals(Sizeval))
        throw new IllegalArgumentException("got it");
    query.addFilterQuery("size:" + Sizeval);
}

request.getParameter("Attr"); returns null, but you are casting the value to String .

When you check if (Sizeval != null) Sizeval has the value "null" instead of being null object.

request.getParameter already returns String or null , so just drop the casting.

Not 100% but:

If 'request.getParameter("Attr")' returns null, and you cast it to a String, isn't this turned into String 'null'?

Got this problem before.

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