user10435687
user10435687

Reputation:

Java empty blocks inside a method different from other blocks?

I understand that a block defines a scope of a variable. And empty blocks inside a method are for setting scope. But why are empty blocks inside methods initialising variables as well unlike in blocks used with loops etc.

class A{
    public static void main(String args[]){
        int a;
        int b:
        {
            a = 10;
        }
        for(int i = 0; i < 1; i++){
            b = 20;
        }
        System.out.println(b); //error here
        System.out.println(a);
        // doesnt give error and prints 10. why?
    }
}

My question is : why are properties of an empty block inside a method not similar to blocks used with loops or conditional blocks etc

Upvotes: 0

Views: 300

Answers (3)

user3438312
user3438312

Reputation: 11

I suspect you are getting a compile and not a runtime error. It's assuming b is never initialized because the compiler assumes the for loop may not execute.

You should always set your variables to a default value, just in case.

Upvotes: 0

Ivan
Ivan

Reputation: 8758

Because that block for a will be executed anyway since there are no enclosing operators. But b is initialized inside loop so compiler sees that b = 20 is executed only inside loop and if loop is not executed that b is not initialized. And compiler doesn't run your code to understand that there are no such code paths where loop is no executed.

Upvotes: 2

CoupFlu
CoupFlu

Reputation: 321

Order of execution.

See the article here:

Order of Execution

Upvotes: 0

Related Questions