Search code examples
javatypesprimitive

What does happen to primitive local variables after a method call?


First of all I'm aware that this question has to be answered somewhere but I seriously couldn't find an answer to this most likely because I'm not searching for the right thing I guess.

So I know about the Java garbage collector, which takes care of unused objects, but what happens with a local value of primitive data type after a method call?

For instance

 public void anyMethod() {
     int foo = 20;
 }

What happens to foo after the Method call? Is it still somewhere in the memory, even if it is never used anymore? Should I even bother caring about such a "technicality"? I know that when it comes to objects only the reference is being processed whereas with primitive value types this is not the case. Maybe I'm also just missunderstanding how primitive values are stored in Java as well

Either way I hope someone can help me out or tell me why my question is stupid and I should feel bad about myself.

Kind regards,


Solution

  • Each function is executed in a stack frame. Method local variables are allocated memory on this stack frame and when the method completes (with or without exceptions), the contents of the stack frame are dropped and all data within it is lost.