Berrigan
Berrigan

Reputation: 438

What happen to temporary Java variables?

What is happening to variable when it is not longer needed. For example

public class Main{
 public static void main(String[] args){
     test();
 }
 public static void test(){
  String testVariable = "test";
  System.out.println(testVariable);   
 } 
}

What is happening to testVariable. Is it being removed from memory, or what. Thanks in advance!

Upvotes: 0

Views: 57

Answers (1)

Sam Estep
Sam Estep

Reputation: 13324

The variable itself (testVariable), which only points to an object, and isn't an object in and of itself, is destroyed immediately when the test method exits, because it is allocated on the stack.

The String object pointed to by testVariable gets garbage collected at some point after Java can prove that there are no more references pointing to it.

Upvotes: 4

Related Questions