2

I have the following code:

for (int i = 0; i < array.length; i++) {
  int current = array[i];
  //do something with current...
}

and the function

int current = 0;
for (int i = 0; i < array.length; i++) {
  current = array[i];
  //do something with current...
}

My question is, do they have the same memory footprint?? I mean, it is clear that the 2nd function will only have 1 variable "current". But how about the first function. Lets assume array has length 1000, does this mean 1000 integeger variables "current" will be created in the inner loop?

matthias
  • 1,938
  • 23
  • 51
  • 1
    Possible duplicate of http://stackoverflow.com/questions/4501482/java-declaring-variables-in-for-loops and http://stackoverflow.com/questions/8803674/declaring-variables-inside-or-outside-of-a-loop – asifsid88 Apr 30 '13 at 09:31

4 Answers4

3

No difference.But IMHO You should generally give variables the smallest scope you can. So declare it inside the loop to limit its scope. You should also initialize variables when they are defined, which is another reason not to declare it outside the loop.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

There is no difference. The compiler is smart enough to generate similar bytecode for both cases by making the right optimizations.

If you want to use the variable outside the loop, declare it outside it, otherwise, in order to give the variable the smallest scope, declare it inside the loop (and consider making it final in this case).

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • @downvoter. Why are you downvoting some of my answers randomly? – Maroun Apr 30 '13 at 17:16
  • 1
    @MAROUN.please ignore those downvotes without valid reasons and keep helping others..No one become king and no one become begger here :) move on... – Suresh Atta Apr 30 '13 at 17:46
  • 1
    @Baadshah Indeed :) I'm here to get help and to help when I can.. Thanks for motivating ;) – Maroun Apr 30 '13 at 17:47
2

They have exactly the same footprint. They even have (without regard to some variable numbering) the exact same bytecode. You can try by putting this in a Test.java, compile it and disassemble it with "javap -c Test"

HTH :)

Markus Duft
  • 151
  • 1
  • 5
1

The two code fragments are equivalent. May even compile to the exact same bytecode (someone will decompile it). Each just creates a single local variable (that is reused in the loop).

Thilo
  • 257,207
  • 101
  • 511
  • 656