6
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

2
  • Is j referred to as a local or a block variable? Commented Oct 19, 2013 at 7:13
  • 2
    j is a block variable which is local to the for loop, ie the block. So it is block variable and local variable with respect to the loop block. Commented Oct 19, 2013 at 7:27

5 Answers 5

10

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 ??"
Sign up to request clarification or add additional context in comments.

10 Comments

Is j referred to as block or local variable?
Classic definition, Local variables are declared in methods, constructors, or blocks. hope you understand :)
Sure I do understand! I'v been hearing this couple of times that it is sometimes referred to as a block variable!
All block variables are local variable's. You can refer in both the ways.
What if the braces of the for loop would be omitted?
|
2

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

Comments

1

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.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.