Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred Way to Reuse Variable in a Loop in Java

Tags:

java

idioms

Out of the following, which is the preferred way of reusing the section vector?

Iterator<Vector> outputIter = parsedOutput.iterator();

while(outputIter.hasNext()) {
    Vector section = outputIter.next();
}

or

Vector section = null;

while(outputIter.hasNext()) {
    section = outputIter.next();
}
like image 754
Alex Bliskovsky Avatar asked Aug 29 '26 13:08

Alex Bliskovsky


1 Answers

The second way means that the variable section is visible outside the loop. If you're not using it outside of the loop, then there's no need to do that, so use the first option. As far as performance, there shouldn't be any visible difference.

like image 112
Mike Baranczak Avatar answered Sep 01 '26 02:09

Mike Baranczak