Conditional statement true in both parts of if-else-if ladder

conditional-statements, if-statement, java

Solution

No, they won't both execute. It goes in order of how you've written them, and logically this makes sense; Even though the second one reads 'else if', you can still think of it as 'else'.

Consider a typical if/else block:

if(true){
   // Blah
} else{
   // Blah blah
}

If your first statement is true, you don't even bother looking at what needs to be done in the else case, because it is irrelevant. Similarly, if you have 'if/elseif', you won't waste your time looking at succeeding blocks because the first one is true.

A real world example could be assigning grades. You might try something like this:

if(grade > 90){
   // Student gets A
} else if(grade > 80){
   // Student gets B
} else if(grade > 70){
   // Student gets c
}

If the student got a 99%, all of these conditions are true. However, you're not going to assign the student A, B and C.

That's why order is important. If I executed this code, and put the B block before the A block, you would assign that same student with a B instead of an A, because the A block wouldn't be executed.

Problem

If you have code like this: ``` if (A > X && B > Y) { Action1(); } else if(A > X || B > Y) { Action2(); } ``` With `A > X` and `B > Y`, will both parts of the `if-else-if` ladder be executed? I'm dealing with Java code where this is present. I normally work in C++, but am an extremely new (and sporadic) programmer in both languages.

Original source