Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are local variables made inside a loop destroyed when the loop starts over?

Tags:

java

loops

memory

while(condition){
    int n=1;
}

Will the variable n be destroyed (the memory being represented by the variable is set to a "null" state) when the loop starts over or will n be declared a second time taking up more memory and they won't be destroyed until the loop exits?

like image 745
Andrew900460 Avatar asked Nov 11 '15 02:11

Andrew900460


1 Answers

At the end of each loop iteration, the variable goes out of scope and ceases to exist. That doesn't mean assigning a special value (such as null) to it; it just means that the memory is available to be used by other things. In any sane JVM implementation, the next iteration of the loop will reuse the same location in memory (and reinitialize its value to 1), so you're using a constant amount of memory no matter how many iterations the loop runs. Note that even though the memory is (probably) reused, it's technically a different variable each time.

Beyond the end of the loop, the variable is permanently out of scope. The memory that it occupies is typically part of the "stack frame" that the JVM creates for all the variables used within the method, so those four bytes are still in-use by the method until it returns, but they can be reused to store another variable that's created later in the same method (if there is one).

Note that an int variable is a primitive type, not an object reference: you can't assign null to it.


A few other answers have mentioned garbage collection. I'd like to clarify that that's actually not relevant here. Objects are garbage-collected, but variables — including those that refer to objects — are not.

A variable is always part of something else: it might be a field in an object, or a static field in a class, or a local variable within a method. Fields within objects have their memory freed when the containing object is garbage-collected, and static fields in classes are released when the class is unloaded (though that usually doesn't happen until the whole program ends). But local variables within a method are stored in the method's stack frame, which is allocated when the method is called, and released when the method returns.

In short: garbage collection is used to find objects that are no longer needed, but there's no need for garbage collection on stack frames because the JVM knows exactly when they're no longer needed: when the method returns.

like image 200
Wyzard Avatar answered Sep 29 '22 00:09

Wyzard