The big difference is that with the else
, the second condition will not be checked at all if the first condition was true. Without the else
, the second condition will be checked.
Ramifications of that:
- If the conditions are not mutually-exclusive, without the
else
both could match and both if
bodies could be executed.
- If the conditions involve side effects, without the
else
the second evaluation will trigger the side-effect a second time.
- As dasblinkenlight pointed out in a now-deleted comment below (and now in his answer), if
x
is a volatile field and its value is changed by another thread after the first check and before the second, without the else
both conditions could match and both if
bodies could be executed.
To see what I mean about evaluation, let's make x
a function call with a side effect instead of just a variable (Java and JavaScript are very different, but in this case, we can use JavaScript to demonstrate the concept):
function x() {
console.log("x called");
return 42;
}
console.log("With else:");
if (x() > 1) {
console.log("> 1");
} else if (x() < 1) {
console.log("< 1");
}
console.log("Without else:");
if (x() > 1) {
console.log("> 1");
}
if (x() < 1) {
console.log("< 1");
}
.as-console-wrapper {
max-height: 100% !important;
}
Note that x
is called twice without the else
, but only once with the else
.