Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Logical Tests in Java

Status
Not open for further replies.

Spab23

Programmer
Jul 22, 2003
43
CA
Can anyone here confirm that Java doesn't necessarily perform each conditional in an "if" statement, if the first few parts of it will determine its outcome?

For example, if I have three conditionals ANDed together and the first one is false, then are the other two tested?

The reason I ask is I have a multiple OR conditional and one of the conditions might result in a NullPointerException if it is executed. I do have a test for nulls earlier in the expression.

My assumption is that:
Code:
if (action == null || (action.indexOf("string") > -1))
...will never give a NullPointerException, but
Code:
if ((action.indexOf("string") > -1) || action == null)
...will give a NullPointerException if "action" is null.

Am I right in assuming this?

Thanks for your help!
 
In theory yes... Inless action.indexOf() is overridden and uses another pointer that happens to be null.

short and sweet:
Code:
if (A && B) // if A is true check B
            //    if B is true do this stuff
            //    else do that stuff
            // if A is false, do that stuff (without checking B)
{
  //this stuff
}
else
{
  //that stuff
}

[plug=shameless]
[/plug]
 
In theory yes... Inless action.indexOf() is overridden and uses another pointer that happens to be null.

short and sweet:
Code:
if (A && B) // if A is true check B
            //    if B is true do this stuff
            //    else do that stuff
            // if A is false, do that stuff (without checking B)
{
  //this stuff
}
else
{
  //that stuff
}

With OR:
Code:
if (A && B) // if A is true do this stuff (without checking B)
            // if A is false, check B
            //     if B is true do this stuff
            //     else do that stuff
{
  //this stuff
}
else
{
  //that stuff
}

[plug=shameless]
[/plug]
 
Spab23, yes your assumption is correct - I believe its called "short circuit conditional statements" or something like that.

jstreich,

I think you need to be careful what types you perform bitwise operations on :)

--------------------------------------------------
Free Database Connection Pooling Software
 
Another way to call it it's a lazy strategy, i've been working with that for a while.

The way to use the eager evaluation in the same case could be the use of bit to bit & operation.

Cheers,

Dian
 
Thanks for all of your confirmations!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top