Home > other >  What is the immediate next block wrapped in curly braces after the if block in Java? [duplicate]
What is the immediate next block wrapped in curly braces after the if block in Java? [duplicate]

Time:10-08

Recently, I received a piece of code like this, but I don't understand what is the next block right after the if block?

for(byte i = 0; i < 5; i  ) {
    P: {
        if(condition) {
            break P;
        }
        {// what is the syntax of this?
            System.out.println("Is else block? no!");
        }
    }
}

At first, I thought it was shorthand for else, but I read a lot of documentation on Oracle and when I run the test, even though the condition of if above is satisfied, the code inside that block also is still executed, so I know it's not else.

So in the end, what was that block?

Your answer solved my question, I would appreciate it.

CodePudding user response:

I'm not sure if it has an official name, but I call these "scope blocks". They're present in C/C and other C-inspired languages as well, mostly as a syntactic consequence of if / else / while / for block syntax - those commands technically take exactly one expression afterwards (and you can see this by using if without a curly bracket afterwards). Using a scope block means the entire block is that expression.

// without a scope block, only one expression
if (condition)
    expression

// vs

// with a scope block, the entire block counts as the one expression
if (condition) 
{
    expression1
    expression2
    ...
}

As for naked scope blocks, they're not very useful. For practical purposes, the inside of the block is its own nested scope (once the block is exited, variables declared inside of it will no longer be available). That's the only real practical purpose of this; otherwise, it's the same as normal code.

CodePudding user response:

It is just a Block. You can put a Block everywhere, where a single statement possible. Such a Block has an own variable scope. Any variable create there is not visible outside.

  • Related