Drew
Drew

Reputation: 15

Nested if-else vs if-else?

I'm confused on what is meant by "nested if-else statements", compared to if-else if statements.

The following question asks to use it instead of if-else statements but I can't figure out how.

if (playerThrow == ROCK && computerThrow == ROCK) {
    System.out.println("Its a draw!");
} else if (playerThrow == ROCK && computerThrow == PAPER) {
    System.out.println("Computer wins!");
} else if (playerThrow == ROCK && computerThrow == SCISSORS) {
    System.out.println("Player wins!");
} /* ... */

Code is from my textbook (I messed up), else I would have posted mine, sorry

Upvotes: 0

Views: 12095

Answers (3)

Jiss Abraham
Jiss Abraham

Reputation: 1



  1. Nested if()...else statements take more execution time (they are slower) in comparison to an else if()... ladder.
  2. The nested if()...else statements check all the inner conditional statements once the outer conditional if() statement is satisfied. whereas the else if()... ladder will stop condition testing once any of the if() or the else if() conditional statements are true.

Upvotes: 0

m_callens
m_callens

Reputation: 6360

A nested if statement is essentially a series of if statements within each other like so...

if (<condition>)
{
    if (<condition>)
    {
       ...
    } else {
       ...
    }
} else {
    ...
}

If-else if statements make using multiple conditions cleaner and easier to read, all being on the same level, like so:

if (<condition 1>)
{
    ...
}
else if (<condition 2>)
{
    ...
}
else
{
    ...
}

Upvotes: 2

ggdx
ggdx

Reputation: 3064

Nested if/else means a heirachy so..

if($something == true){
    if($something_else == true){
    } else {
    }
} else { // $something == false
    if($something_else == true){
    } else {
    }
}

Upvotes: 2

Related Questions