Inside
for(int i = 0; i < array.length; i++) {
final String variable = array[i];
}
- Keeps scope of variables limited.
- Variable can be final
- More readable (maybe)
Outside
String variable;
for(int i = 0; i < array.length; i++) {
variable = array[i];
}
- Variable is accessible outside loop.
For Each
for(final String variable : array) {
}
- Only allocates once (source needed)
- Keeps scope of variable limited.
- Looks frickin' awesome.
Performance
The following test was run. It takes approximately 30s to run. The results show that there is no difference in performance between defining the variable inside or outside of the loop. This is most likely due to compiler optimizations. YMMV.
final double MAX = 1e7;
long start = System.nanoTime();
String var1;
for(double i = 0; i < MAX; i++) {
var1 = UUID.randomUUID().toString();
}
System.out.println((System.nanoTime() - start) / 1e9);
start = System.nanoTime();
for(double i = 0; i < MAX; i++) {
final String var2 = UUID.randomUUID().toString();
}
System.out.println((System.nanoTime() - start) / 1e9);
Discussion of Style Preference: https://stackoverflow.com/a/8803806/1669208