How to access variable that is in the while loop from outside it ?
3 Answers
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.
Comments
a) don't. it's a bad idea
b) Define it outside the loop
int x;
while(something){
x = somethingElse;
}
3 Comments
T.J. Crowder
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.
Synesso
Agree. In an imperative language this is how loop constructs are used to build state.
Sean Patrick Floyd
Ok my answer sounded too harsh. I agree it's sometimes necessary.