• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 194
  • Last Modified:

QUICKIE: Safe to check for null and valid value in same statement?

Dear Experts:

In Java, is it always safe to do this:

Integer myInt;

// .. do some things...

if ((myInt != null) & (myInt.intValue() != 999))
{
  // did I blow up?
}

Is the test for null ALWAYS done first, so there is no risk of NullPointerException?

Thanks,
BrianMc1958
0
BrianMc1958
Asked:
BrianMc1958
  • 4
1 Solution
 
zzynxSoftware engineerCommented:
>> Is the test for null ALWAYS done first
Yes
>> so there is no risk of NullPointerException
No
0
 
zzynxSoftware engineerCommented:
I guess you meant "&&" instead of "&"
0
 
zzynxSoftware engineerCommented:
>>>> Is the test for null ALWAYS done first
>>Yes
I mean: the left most part is always done first  (if you put "myInt!=null" as 2nd part NPE's can occur)

>>>> so there is no risk of NullPointerException
>>No
That's because if myInt==null the first part is false.
In that case the 2nd part is no longer validated, since it's useless.
Because
    false && whatever is always false
0
 
TimYatesCommented:
Java == "Lazy Evaluation", so zzynx is right.

http://mindprod.com/jgloss/lazy.html
0
 
zzynxSoftware engineerCommented:
Thanks for accepting
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now