Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable declaration inside a loop

Tags:

java

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?

like image 478
Amit Avatar asked Jan 05 '10 08:01

Amit


People also ask

Can I declare a variable inside a loop?

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.

Can you initialize variables in a for loop in C?

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.

Can you declare two variables in a for loop in C?

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.


1 Answers

Declaring it inside the loop won't cause any harm to the memory and performance.

like image 172
missingfaktor Avatar answered Sep 27 '22 23:09

missingfaktor