IF statement - && vs nested statements?
Hello, newbie here :D
I'm just wondering if there is any difference in whether I use && compared to using nested if statements.
int count = 2;
int total = 4;
//---------------
// Using &&
//---------------
if (count == 2 && total == 4)
{
System.out.println ("2 + X = 4");
}
//------------------------------
// Compared to using nested statements
//-------------------------------
if (count == 2)
{
if (total == 4)
{
System.out.println ("2+X=4");
}
}
my textbook says, "This type of processing should be used carefully" in regards to using && and having the process "short circuit". So is using nested if statements better for some reason?
Re: IF statement - && vs nested statements?
You have a nice tool in your JDK: javap.exe; it can disassemble the class code in a .class file. Try it and see what code is produced for your example and judge for yourself. (look in your JDK/bin directory, it should be in your PATH environment variable).
kind regards,
Jos
Re: IF statement - && vs nested statements?
Could you point me in the right direction on how to use it in Eclipse?
Re: IF statement - && vs nested statements?
Quote:
Originally Posted by
NewbieDan
Could you point me in the right direction on how to use it in Eclipse?
Not everything needs to be done with Eclipse; fire up a shell/command prompt; go to the directory where your .class file is stored and type this:
Code:
javap -c YourClassFile
javap produces a listing of the disassembled code in YourClassFile.
kind regards,
Jos
Re: IF statement - && vs nested statements?
Quote:
Originally Posted by
NewbieDan
my textbook says, "This type of processing should be used carefully" in regards to using && and having the process "short circuit". So is using nested if statements better for some reason?
The only thing you need to be careful with regards to short-circuiting is that if the left-hand operand of && evaluates to false, or the left-hand operand of || evaluates to true, the right-hand operand won't be evaluated at all. So if you have something like:
Code:
if (a-- > 0 && b++ <= 100) { ... }
then, if a <= 0, a will be decremented but b will not be incremented. If you need both operands to be evaluated, you can use the & operator.