# Thread: IF statement - && vs nested statements?

1. Member
Join Date
Oct 2011
Posts
7
Rep Power
0

## 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?
Last edited by NewbieDan; 10-23-2011 at 12:58 AM.

2. ## 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

3. Member
Join Date
Oct 2011
Posts
7
Rep Power
0

## Re: IF statement - && vs nested statements?

Could you point me in the right direction on how to use it in Eclipse?

4. ## Re: IF statement - && vs nested statements?

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:

Java Code:
`javap -c YourClassFile`
javap produces a listing of the disassembled code in YourClassFile.

kind regards,

Jos

5. Senior Member
Join Date
Nov 2010
Posts
210
Rep Power
7

## Re: IF statement - && vs nested statements?

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:

Java 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•