Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Declaring variables in for loops

Is declaring a variable inside of a loop poor practice? It would seem to me that doing so, as seen in the first code block below, would use ten times the memory as the second... due to creating a new string in each iteration of the loop. Is this correct?

for (int i = 0; i < 10; i++) {
  String str = "Some string";
}

vs.

String str;
for (int i = 0; i < 10; i++) {
  str = "Some String";
}
like image 253
dfetter88 Avatar asked Dec 21 '10 16:12

dfetter88


People also ask

Can I declare variable in for loop Java?

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.

Is it good to declare variable inside for loop in Java?

But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used).

Should you declare variables in loops?

It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope. What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs.

Can you declare two variables in a for loop Java?

In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.


1 Answers

Is declaring a variable inside of a loop poor practice?

Not at all! It localizes the variable to its point-of-use.

It would seem to me that doing so, as seen in the first code block below, would use ten times the memory as the second

The compiler may optimize things to keep memory use efficient. FYI: you can help it, if you use the final keyword to tell it that your variable has a fixed reference to an object.

Note: if you have a more complex object where you are executing complex code in the constructor, then you may need to worry about single vs. multiple executions, and declare the object outside of the loop.

like image 81
Jason S Avatar answered Oct 01 '22 13:10

Jason S