AVINASH
AVINASH

Reputation: 108

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

Upvotes: 0

Views: 200

Answers (3)

wero
wero

Reputation: 32980

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);
}

Upvotes: 3

Guy
Guy

Reputation: 50809

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.

Upvotes: 1

Wesley De Keirsmaeker
Wesley De Keirsmaeker

Reputation: 1025

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.

Upvotes: -1

Related Questions