mercredi 28 janvier 2015

else if comparison - compiler standpoint

Are these blocks of code identical? By identical I mean, does the compiler interpret them exactly the same way?



int i = 2;
if (i == 0) {
System.out.println("0!");
} else if (i == 1) {
System.out.println("1!");
} else if (i == 2) {
System.out.println("2!");
} else {
System.out.println("?!");
}





int i = 2;
if (i == 0) {
System.out.println("0!");
} else {
if (i == 1) {
System.out.println("1!");
} else {
if (i == 2) {
System.out.println("2!");
} else {
System.out.println("?!");
}
}
}


As you can see this is Java.


While both my friend and I agree that logically these are exactly the same, I was wondering whether the java compiler compiles them exactly the same way. The thing that strikes me is that in the second else/if block you are nesting ifs and elses inside of the else block.


However, given my lack of knowledge in assembly or java byte code, this very well could compile to be completely identical. The only advantage could be syntactical sugar, if you will.


Will someone put this issue to rest - assuming you are extremely confident in the answer (otherwise another debate might ensue).


Aucun commentaire:

Enregistrer un commentaire