Scope of variable declared inside a for loop

后端 未结 5 504
挽巷
挽巷 2020-11-30 15:18
for(int i=0; i<10;i++){
 int j=0;
}

Is j a block variable or a local variable? I see that j\'s scope is only till the for loop ends

相关标签:
5条回答
  • 2020-11-30 15:44

    j has scope in the loop only, outside the loop, j can not be accessed. For more on scopes, refer the link, it will be helpful.

    0 讨论(0)
  • 2020-11-30 15:48

    The word "local" means that something is available somewhere, but not outside the bounds of this "somewhere". In Java variables declared inside a block have a block scope, which means that they're available only inside this block - they're local to it.

    0 讨论(0)
  • 2020-11-30 15:59

    It is a local variable to that for block. Outside of that for loop, j will cease to exist.

    0 讨论(0)
  • 2020-11-30 16:07

    Local variables are declared in methods, constructors, or blocks.

    From that it's clear that, All block variables are local variable's.

    As per definition of Block

    A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.

    So

    {   //block started
    
    }    //block ended
    

    What ever the variables declared inside the block ,the scope restricted to that block.

    for(int i=0; i<10;i++){
     int j=0;
    }
    

    So J scope is restricted to inside that block. That is for loop.

    for(int i=0; i<10;i++){
     int j=0;
     //do some thing with j ---> compiler says "yes boss"
    }
    //do some thing with j ---> compiler says "Sorry boss, what is j ??"
    
    0 讨论(0)
  • 2020-11-30 16:11

    j variable is accessible inside {this block} only. That not only means that it can't be changed anywhere else, but also it is recreated every time loop loops.

    0 讨论(0)
提交回复
热议问题