Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two IF statements vs. one AND statement

Within java I wonder which of these is more efficient:

if(something)
   {
      if(something)
    }

or

if((something) &&(something))

I was wondering what the merits are for both in terms of performance. Which solutions lend themselves better to different data objects.

like image 307
Will Avatar asked Mar 06 '12 11:03

Will


People also ask

Can there be 2 if statements?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

Can you have 2 if statements in Excel?

While Excel will allow you to nest up to 64 different IF functions, it's not at all advisable to do so.

What is better than multiple if statements?

Switch statement works better than multiple if statements when you are giving input directly without any condition checking in the statements. Switch statement works well when you want to increase the readability of the code and many alternative available.

Can you have multiple && in an if statement?

you can use as many && and || as you want. i've seen as many as 27 conditions all ANDed and ORed together.


2 Answers

Performance will be identical. The first statement will be evaluated and only if it is true will the second one be evaluated.

This is merely a question of readability. Unless there is something that needs to be done if the first statement is true, regardless of the second, I'd go with both in the same line as it is clearer that both statements need to be true for something to happen. You also don't have to indent unnecessarily.

like image 66
Kris Avatar answered Oct 03 '22 19:10

Kris


In Java, && short-circuits. This means that if the first condition in a && b evaluates to false, the second condition isn't even evaluated.

Therefore, the two almost certainly result in identical code, and there's no performance difference.

Of the two forms, you should use whichever results in clearer code.

like image 43
NPE Avatar answered Oct 03 '22 18:10

NPE