0

Is there a way to make a variable that is declared inside a loop be able to be called from outside that for loop?

3
  • 7
    No, that's the whole point of scope. Commented Apr 11, 2016 at 17:28
  • 1
    yes declare it outside of the for loop Commented Apr 11, 2016 at 17:28
  • 2
    I am not sure why this question has so many down-votes. It is honest question of newbie which probably most of us asked once in our life when we started learning programming/Java (or language with similar rules). Commented Apr 11, 2016 at 17:59

3 Answers 3

1

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

Comments

1

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.

1 Comment

Would the variable be changed by the code that is inside the loop?
1

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

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.