0

How to access variable that is in the while loop from outside it ?

3 Answers 3

5

Always declare variables at the scope that makes sense. If your variable is to be referenced both inside and outside a loop, then it must be declared outside the loop.

public String doIt() {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < 100; i++) {
        builder.append("ponies ");
    }
    return builder.toString();
}

It is good practice to narrow the scope of variables so that they are only visible where they are needed.

Sign up to request clarification or add additional context in comments.

Comments

3

a) don't. it's a bad idea

b) Define it outside the loop

int x;
while(something){
    x = somethingElse;
}

3 Comments

Re (a): Recommend removing that part of your answer. This can be a perfectly reasonable thing to do. Like almost everything else in programming, it can be abused, but is not necessarily wrong.
Agree. In an imperative language this is how loop constructs are used to build state.
Ok my answer sounded too harsh. I agree it's sometimes necessary.
2

Declare the variable outside the loop.

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.