One common dilemma I have faced throughout programming is regarding declaring variables inside a loop. Say I have to perform something like the following:
List list=myObject.getList();
Iterator itr=list.iterator();
while (itr.hasNext()){
BusinessObject myBo=(BusinessObject)itr.next();
process(myBo);
}
In the above snippet, should myBo
be declared outside the loop or does declaring it inside the loop not cause harm to memory and performance?
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
Syntax. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas.
Declaring it inside the loop won't cause any harm to the memory and performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With