Chris Britt Chris Britt - 3 months ago 9
Java Question

Java else-if vs else{if}

I have been curious about this for some time, but never found a good definitive answer. While "best practice" for code clarity of using an if-else-if block is to write it as follows:

if (conditionA) {
...
} else if (conditionB) {
...
} else {
...
}


Does this code differ in the bytecode generated (and thus the speed of execution) from the alternative method of writing:

if (conditionA) {
...
} else {
if (conditionB) {
...
} else {
...
}
}


If these two different methods are compiled differently, which will be faster?

Answer

The speed of execution doesn't depend on irrelevant things like this. Check out the generated bytecode with javap, they probably produce identical bytecode meaning that the only reason to use the latter style is if you want other programmers to look at you weirdly┬╣.

┬╣ The first way is the idiomatic way to write it, so experienced developers would most likely find the latter way strange and unnecessary.