samedi 9 novembre 2019

Is there an else if in Java? [duplicate]

For some time now, I've been thinking that there actually is no else if in Java. Just if and else.

In Java we can leave out the curly brackets after a conditional statement if there is only a single instruction or code block following.

So the following code:

if(a < 1) {
    // ...
} else {
    if (a < 2) {
        // ...
    } else {
        // ...
    }
}

can also be written as:

if(a < 1) {
    // ...
} else 
    if (a < 2) {
        // ...
    } else {
        // ...
    }

which is the same as:

if (a < 1) {
    // ...
} else if (a < 2) {
    // ...
} else {
    // ...
}

I've checked the produced bytecode and it's also identical.
So in the end an else if is just an else block containing another if.

Sure we're taught about the else if conditional statement, like on w3schools:

Java has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false

Now I'm wondering if the Java syntax actually contains else if as distinct statement from if and else or if the Java compiler just sees it as the later two.

Aucun commentaire:

Enregistrer un commentaire