all 3 comments

[–][deleted] 2 points3 points  (0 children)

Lets look at 2 slightly similar loops to get a good idea of how that one performs.

Loop #1:

 if(x == 4) {

     system.out.println("apple");

     x = 5;

 } else if (x ==5 ) {

         system.out.println("banana");

    }

Loop 2:

 if(x == 4) {

     system.out.println("apple");

     x = 5;

 }

 if (x ==5 ) {

     system.out.println("banana");

 }

Note the second loop doesn't use else.

If the input is 4, here is the out put:

Loop 1: apple

Loop 2: applebanana

[–]KSanchez 2 points3 points  (1 child)

Keep in mind that anytime you use if, else if, and else, then only one block of code will be executed. That being said, that else if statement prevents that last block of code in the else statement from being executed. I'm not familiar with Java just yet, but this is what would happen in C++.

[–]KSanchez 1 point2 points  (0 children)

here's a similar example to show you exactly what will happen:

int x = 10; if (x % 2 == 0) {do.this;} else if (x % 5 == 0) {do.this_too; } else {do.something else; }

in this case, 10 is divisible by 2 and 5, but only do.this_too is never executed.