The second is what I would prefer. There is no functional difference, except for the field of view.
Setting the same variable in each iteration does not matter, because Integer is an immutable class. Now, if you changed an object each time, and not each time created a new one, then there would be a difference.
And as a note, in this code you should use int and Integer.parseInt() , not Integer and Integer.parse() . You introduce quite a bit of unnecessary boxing and unboxing.
Edit: It has been a while since I retired to the bytecode, so I thought I'd hold my hands again.
Here's the test class I compiled:
class ScopeTest { public void outside(String[] args) { Integer total = 0; Integer i; for (String str : args) { i = Integer.valueOf(str); total += i; } } public void inside(String[] args) { Integer total = 0; for (String str : args) { Integer i = Integer.valueOf(str); total += i; } } }
Bytecode output (obtained after javap -c ScopeTest after compilation):
Compiled from "ScopeTest.java" class ScopeTest extends java.lang.Object{ ScopeTest(); Code: 0: aload_0 1: invokespecial
Unlike my expectations, there was one difference between them: in outside() variable i still occupied the register, even if it was excluded from the actual code (note that all iload and istore instructions indicate the same register above).
The JIT compiler should do a short job with this difference, but still you can see that the bounding area is good practice.
(As for my previous post, you can see that to add two Integer objects, Java must unzip both with intValue , add them, and then create a new Integer with valueOf . This, if absolutely necessary, because it makes no sense and is slower.)