Reputation: 2265
What are the differences between this:
if(a && b)
{
//code
}
and this:
if(a)
{
if(b)
{
//code
}
}
From what I know b
will only get evaluated in the first code block if a
is true, and the second code block would be the same thing.
Are there any benefits of using one over the other? Code execution time? memory? etc.
Upvotes: 4
Views: 924
Reputation: 5607
It makes a difference if you have an else associated with each if.
if(a && b)
{
//do something if both a and b evaluate to true
} else {
//do something if either of a or b is false
}
and this:
if(a)
{
if(b)
{
//do something if both a and b are true
} else {
//do something if only a is true
}
} else {
if(b)
{
//do something if only b is true
} else {
//do something if both a and b are false
}
}
Upvotes: 4
Reputation: 13596
They get compiled to the same bytecode. No performance difference.
Readability is the only difference. As a huge generalization, short-circuiting looks better but nesting is slightly clearer. It really boils down to the specific use case. I'd typically short-circuit.
I tried this out. Here's the code:
public class Test {
public static void main(String[] args) {
boolean a = 1>0;
boolean b = 0>1;
if (a && b)
System.out.println(5);
if (a)
if (b)
System.out.println(5);
}
}
This compiles to:
0: iconst_1
1: istore_1
2: iconst_0
3: istore_2
4: iload_1
5: ifeq 19
8: iload_2
9: ifeq 19
12: getstatic #2
15: iconst_5
16: invokevirtual #3
19: iload_1
20: ifeq 34
23: iload_2
24: ifeq 34
27: getstatic #2
30: iconst_5
31: invokevirtual #3
34: return
Note how this block repeats twice:
4: iload_1
5: ifeq 19
8: iload_2
9: ifeq 19
12: getstatic #2
15: iconst_5
16: invokevirtual #3
Same bytecode both times.
Upvotes: 8
Reputation: 8481
there shouldn't be a difference, but in readability I would prefer the first one, because it is less verbose and less indented.
Upvotes: 0
Reputation: 68715
If there is nothing in between two if
statements in your second example then definitely first one is more cleaner and more readable.
But if there is a piece of code that could fit in between the two if conditions then only way is second example.
Upvotes: 0