Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will local variables declared in a Java function automatically be deallocated?

If a variable is declared within a function in Java, will that variable be deallocated automatically upon that function's completion regardless of its type? Would the memory occupied by a primitive type, a non-primitive Object, and/or an array of either primitives or Objects be freed up once that variable's scope has been exited?

like image 561
user2649681 Avatar asked Jan 26 '15 02:01

user2649681


1 Answers

Primitive types in Java are allocated on the stack, so their memory is automatically deallocated when they go out of scope. Object references are primitives which are similarly managed, but the objects themselves are garbage collected. They will be removed automatically by the garbage collector, but it is not guaranteed how long that will take.

The JVM garbage collector automatically runs when the memory pressure becomes tight, so as long as there are no references to an object anymore, you can effectively make the assumption that its memory will be freed.

like image 175
Alexis King Avatar answered Sep 30 '22 19:09

Alexis King