Reputation: 78
Is there a way to make a variable that is declared inside a loop be able to be called from outside that for loop?
Upvotes: 0
Views: 1291
Reputation: 75
variables that are declared within a block cannot be accessed outside of that block.Their scope and lifetime is limited to the block.However for a variable declared outside the block, its value can be changed inside the block and same the value will be reflected once you come out of the block.For a better understanding you can go through this link http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm
Upvotes: 1
Reputation: 43078
If you need the object when the loop is finished, you need to create a reference to it that still exists after the loop is finished. So do this
Object pointer = null;
for (int v = 0; v < n; v++) {
...
pointer = myObj;
}
// use pointer here
If you don't want that object sticking around after you are done with it, say you need to only use it for one thing after the loop, then you can create it in it's own scope like this:
{
Object pointer = null;
for (int v = 0; v < n; v++) {
...
pointer = myObj;
}
// use pointer here
}
// pointer no longer exists here
Following this logic, you can even create the scope inside the loop itself
for (int v = 0; v < n; v++) {
...
{
// If loop is done, now use the myObj
}
}
And finally, why not just get rid of the scope and use the obj inside the loop?
for (int v = 0; v < n; v++) {
...
// If loop is done, now use the myObj
}
Upvotes: 1
Reputation: 1777
If you create a variable in a loop (or any set of curly braces) its scope is only the body of that loop. You would have to create the variable before hand and set it in the loop.
Upvotes: 1