-4

I am asking this question for my clarification.

I am having a for loop inside of which I have some inner method. when I used "i" in this inner method the IDE keeps asking me to make it "i" as final.

for(int i=0; i<array.size();i++) {

     some innermethodcode(){
     Log.e("array",""+array.get(i)); // it says me make it final;

    }

What would happen if I declared "i" as global like

int i ;

; or what would be different if I declared "i" as

int i = 0;

And use it as

for(i=0; i<array.size();i++) {

         some innermethodcode(){
         Log.e("array",""+array.get(i)); // it says me make it final;

        }

would it result in completly unpredictable values of "i" because the place that uses it is not executed the same time the loop runs ?

EDIT

I am very much knowing about how to get a final variable from a loop variable like this:

for (int i = 0; i < 10; i++) {
    final int j = i;
    // now you can use j instead
}

My question is why i need to make final and what would happen if I declared it as global.

Please help me to clarify this.

Thanks in advance.

Bö macht Blau
  • 12,820
  • 5
  • 40
  • 61
KishuDroid
  • 5,411
  • 4
  • 30
  • 47

2 Answers2

2

I think you are mistaking is for an anonymous inner class. Have a look at this stackoverflow answer.

Community
  • 1
  • 1
AbhishekAsh
  • 421
  • 2
  • 15
0

It doesn't matter where you declare it, it needs to be final. The way to use a loop index like this is to use a second variable.

for (int i = 0; i < 10; i++) {
    final int j = i;
    // now you can use j instead
}
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116