Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of variable declared inside a for loop

Tags:

java

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

like image 637
Mercenary Avatar asked Dec 15 '22 05:12

Mercenary


2 Answers

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 ??"
like image 92
Suresh Atta Avatar answered Dec 23 '22 13:12

Suresh Atta


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

like image 35
dckuehn Avatar answered Dec 23 '22 14:12

dckuehn