0

i want to get parameters values and sometimes i do not send them and it return me null and its ok . but when i preform check on the return string array the servlet throws a java.lang.NullPointerException

and i just what to do nothing when its null. ( continue the flow )

String[] values = null; 
if(request.getParameterValues(fieldName).length>0)
{
    values = request.getParameterValues(fieldName);

    if(null!=values || values.length>0) // HERE IT throws NullPointerException 
    {
        Collections.addAll(strlist, values);
    }
}
blackpanther
  • 10,998
  • 11
  • 48
  • 78
user63898
  • 29,839
  • 85
  • 272
  • 514

4 Answers4

6

It should be

if(null!=values && values.length>0)

because, if your values is null(evaluating to false), the OR condition in your statement, executes the other part of the OR, which throws the NPE.

If you give an && there, it'll SHORT-CIRCUIT the statement evaluation when it encounters a false at null!=values.

Rahul
  • 44,383
  • 11
  • 84
  • 103
  • why , i what to check or this or that condition – user63898 Apr 29 '13 at 07:47
  • @user63898 If you check using OR, then although `values` is null, you'll still do `values.length` which will throw NPE. If you have `&&`, if `values` is null, the second part won't be checked since `false && no_matter_what` is always false. – Maroun Apr 29 '13 at 07:49
  • You can't do that. If you do it, then you're bound to get that exception! If values is `null`, `null.length` is bound to give you `NPE`. – Rahul Apr 29 '13 at 07:50
1

It's the AND && operator that should be used to test if both conditions are met, which is what you need in you instance.

if (null != values && values.length > 0)
blackpanther
  • 10,998
  • 11
  • 48
  • 78
0

in and unlike or if values is null it wont go for next check.

if(null!=values && values.length>0) // change to and 
 {
         Collections.addAll(strlist, values);
 }

also refer && (AND) and || (OR) in IF statements

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

&& and || follow short-circuit evaluation.

That is these operators wont execute right side expressions if not needed.

for && operator if false at LHS, then it wont execute next expressions
for || operator if true at LHS, then it wont execute next expressions

so for your condition check it needs && operation for avoiding NullPointerException

if(null!=values && values.length>0)
NamingException
  • 2,388
  • 1
  • 19
  • 41